My code is :
Object value = tasks.get(key);
result value
is : [{"name":"one","family":"yes"},{"name":"two","family":"no"}]
Now i want get child of value
in foreach
foreach(...){
String name = ...
String family = ...
}
My code is :
Object value = tasks.get(key);
result value
is : [{"name":"one","family":"yes"},{"name":"two","family":"no"}]
Now i want get child of value
in foreach
foreach(...){
String name = ...
String family = ...
}
Your value is in JSONArray format.
Use this:
JSONArray values = new JSONArray((String) tasks.get(key)); // or alternative task.getString(key)
for (int i = 0; i < values.length(); i++) {
JSONObject entry = values.getJSONObject(i);
String name = entry.getString("name");
String family = entry.getString("family");
}
Object itself not containig fields or something, you have to create pojo
(just if you want clean and resuseble code) in order to get fields from it, for example, using Gson
Add dependencies:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Add pojo:
public class Pojo{
@SerializedName("name")
@Expose
private String name;
@SerializedName("family")
@Expose
private String family;
}
Convert:
Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonObject.toString(), Pojo.class);
Step 1: Convert Object instance into String
String response = (String) value;
Step 2: Feed the String instance into JsonArray
//don't forget to caught JSONException here
JsonArray array = new JsonArray(response);
Step 3: Iterate through JsonArray and get values from each JsonObject
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
//get values here
String name = object.getString("name");
String family = object.getString("family");
}
Now, the whole code should look like this
try {
JSONArray array = new JSONArray("");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String name = object.getString("name");
String family = object.getString("family");
}
} catch (JSONExceptione) {
//do something..
}
Important If you still don't know what happened, this whole process is called JSON parsing. Learn about it.