Reputation: 69
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" }
]}
Upvotes: 0
Views: 913
Reputation: 777
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);
}
Upvotes: 1