将JSON文件读取到ArrayList

时间:2016-10-27 12:20:18

标签: android json arraylist

我在从JSON文件加载对象时遇到问题,我们的想法是将对象存储在JSON文件中并返回一个对象数组,有没有更简单的方法呢?或者有没有比JSON更好的解决方案呢?

    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" }



]}

1 个答案:

答案 0 :(得分: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);
    }