如何解析以下 JSON 使用 GSON 的 android 吗?

标签: json Android gson
发布时间: 2017/3/4 2:38:25
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

作为 keysArray (A,B,C) 是 dynamiccores 具有相同的对象名称?请帮助!!!

{

 "result":"success",

 "keysArray":[
     "A",
     "B",
     "C",
     "D",
     "E"
     ],

 "cores":{

    "A":[{"key":"value"}],
    "B":[{"key":"value"}],
    "C":[{"key":"value"}],
    "D":[{"key":"value"}],
    "E":[{"key":"value"}]
 }
}

解决方法 1:

我已经达到了它在这种方式。

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

 }
}

任何建议:)

赞助商