How do I use gson to parse the following JSON in Android?
•
Android
Because keysarray (a, B, c) is dynamic, and the core has the same object name? Please help!!!
{
"result":"success",
"keysArray":[
"A",
"B",
"C",
"D",
"E"
],
"cores":{
"A":[{"key":"value"}],
"B":[{"key":"value"}],
"C":[{"key":"value"}],
"D":[{"key":"value"}],
"E":[{"key":"value"}]
}
}
resolvent:
I realized it in this way
String responseStr = //JsonResponse here
Type type = new TypeToken<GetMainResponse>() {}.getType();
GetMainResponse getMainResponse = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create().fromJson(responseStr, type);
int size = getMainResponse.getKeysArray().size();
for (int i = 0; i < size; i++) {
JSONArray jCoreIngredients = new JSONObject(responseStr)
.getJSONArray(getMainResponse.getKeysArray().get(i));
String innerStr = jCoreIngredients.toString();
Type type2 = new TypeToken<ArrayList<GetMainResponse.InnerCores>>() {}.getType();
ArrayList<GetMainResponse.InnerCores> ingredientsInner = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create().fromJson(innerStr, type2);
}
//And this is my POJO
public class GetMainResponse{
String result;
ArrayList<String> keysArray;
Cores cores;
public String getResult() { return result; }
public void setResult(String result) { this.result = result; }
public ArrayList<String> getKeysArray() { return keysArray; }
public void setKeysArray(ArrayList<String> keysArray) { this.keysArray = keysArray; }
public Data getCores() { return data; }
public void setCores(Cores cores) { this.cores = cores; }
public class Cores {
// No declaration and not getter setter here.
public class InnerCores {
String key;
public String getKey() { return key; }
public void setKey(String result) { this.key = key; }
}
}
Any suggestions:)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码