如何在android中使用GSON解析以下JSON

如何在android中使用GSON解析以下JSON

由于 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"}]
 }
}

最佳答案

我已经通过这种方式实现了它。

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

 }
}

有什么建议么 :)

关于android - 如何在android中使用GSON解析以下JSON?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41355969/

10-10 09:25