2016-10-27 78 views
0

我無法從JSON文件中加載對象,想法是將對象存儲在JSON文件中並返回一個對象數組,有沒有更簡單的方法來做到這一點?或者有沒有比JSON更好的解決方案?將JSON文件讀取到ArrayList

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_student_list); 


    TextView studentlistTextView =   (TextView)findViewById(R.id.studentlistTextView); 
    ArrayList<students> studentArray = loadJSONFromAsset(); 
    try { 
     studentlistTextView.setText(studentArray.get(0).getName()); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 

} 
public ArrayList<students> loadJSONFromAsset() { 
    ArrayList<students> studentArray = new ArrayList<>(); 
    String json = null; 
    try { 
     InputStream is = getAssets().open("jsonstudent"); 
     int size = is.available(); 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     json = new String(buffer, "UTF-8"); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
     return null; 
    } 
    try { 
     JSONObject obj = new JSONObject(json); 
     JSONArray m_jArry = obj.getJSONArray("students"); 

     for (int i = 0; i < m_jArry.length(); i++) { 
      JSONObject jo_inside = m_jArry.getJSONObject(i); 
      students student = new students(); 
      student.setName(jo_inside.getString("name")); 
      student.setLastname(jo_inside.getString("lastname")); 
      student.setNumber(jo_inside.getString("number")); 




      studentArray.add(student); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return studentArray; 
} 

} 

這是我的JSON文件

{ "student" : [ 
{"name" : "hans", "lastname" : "rosenboll", "number" : "5325235" } 



]} 
+0

如果是這樣的完成json,將obj.getJSONArray(「students」)更改爲obj.getJSONArray(「student」)並嘗試? – Raghavendra

+0

任何目的將json文件寫入SD卡? – Radhey

回答

1

您可以使用GSON和共享偏好存儲在JSON文件對象,並返回對象的數組:

private final String PERSONAL_INFO = "personal_info"; 

public void putPersonalInfo(Profile info) { 
     Gson gson = new Gson(); 
     String json = gson.toJson(info); 
     getAppPreference().edit().putString(PERSONAL_INFO, json).commit(); 
    } 

    public Profile getPersonalInfo() { 
     Gson gson = new Gson(); 
     return gson.fromJson(getAppPreference().getString(PERSONAL_INFO, null), Profile.class); 
    }