0

I'm having trouble loading objects from an JSON file, the idea is to store objects in the JSON file and return an array of objects, is there any easier way doing this? Or is there any better solution than JSON for doing this?

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

}

This is my JSON file

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



]}
2
  • If that is the complete json, change obj.getJSONArray("students") to obj.getJSONArray("student") and try? Commented Oct 27, 2016 at 12:23
  • any purpose to write json file in to sdcard ? Commented Oct 27, 2016 at 12:28

1 Answer 1

1

You can use Gson and Shared Preference to store objects in the JSON file and return an array of objects:

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.