1.) create a json array by passing a string to the constructor
2.) and return your jsonObject using index i
3.) jsonObject activity jsonObject , and then just use your index to retrieve the values โโfor the jsonActivityItem object.
4.) create a POJO class to store your object in a collection, such as List, etc., but be sure to mark them private and use getters and setters for best practice
class User{ String id,kind,result; int userId,accountId; long timestamp;
Note. To convert your string to json compatible, you can use JsonParser , try this link fragment JsonParser
JSONArray array; List<User> listUser=new ArrayList<>(); // to store objects as details try { array=new JSONArray(st); // st is your string ( make sure to use jsonparser ) JSONObject jsonActivity; JSONObject jsonActivityItem; User user; for (int i=0;i<array.length();i++) { System.out.println(); jsonActivity=array.getJSONObject(i); jsonActivityItem=jsonActivity.getJSONObject("activity");
// To store data for later use user = new User(); user.setId(jsonActivityItem.getString("id")); user.settimestamp(jsonActivityItem.getLong("timestamp")); //..set other values using setters listUser.add(user);
// to display items String id = jsonActivityItem.optString("id"); String kind = jsonActivityItem.optString("kind"); String userId = jsonActivityItem.optString("userId"); String accountId = jsonActivityItem.optString("accountId"); String timestamp = jsonActivityItem.optString("timestamp"); String result = jsonActivityItem.optString("result"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }
I would recommend a simple and short way, i.e. using gson to convert it to a list, but you will need to use the POJO class, you can take a look at this link to create a compatible POJO class, and then just use the Gson code
Validation check . Sometimes you can see some exceptions when the values โโare not available, so in cases where you are not sure about the value, use optInt optBoolean , etc., which will simply return the default value if it is missing, and even try to convert the value to int if it is string like
from docs
Get the optional int value associated with the key, or the default value if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int block_id = jObj.getInt("key",defaultvalue);
eg
int block_id = jObj.getInt("userId",0);