Java 使用GSON解析JSON提要,并获取一个数组而不是多个参数

Java 使用GSON解析JSON提要,并获取一个数组而不是多个参数,java,android,json,parsing,gson,Java,Android,Json,Parsing,Gson,我正试图在Android应用程序上解析一个ELGG resfull webservice() 我使用GSON库将JSON提要转换为JAVA对象,我创建了转换(映射)所需的所有类 问题在于jSON格式(我无法更改): 这种格式的“result”包含许多没有相同名称的子对象(即使它们的结构与我称之为“apiMethod”的结构相同),GSON尝试将其解析为分离对象,但我希望他将所有“result”子对象解析为“apiMethod”对象。您可以使用映射,而不是数组,如果不想在结果对象中定义所有可能的字

我正试图在Android应用程序上解析一个ELGG resfull webservice()

我使用GSON库将JSON提要转换为JAVA对象,我创建了转换(映射)所需的所有类

问题在于jSON格式(我无法更改):


这种格式的“result”包含许多没有相同名称的子对象(即使它们的结构与我称之为“apiMethod”的结构相同),GSON尝试将其解析为分离对象,但我希望他将所有“result”子对象解析为“apiMethod”对象。

您可以使用
映射,而不是数组,如果不想在
结果
对象中定义所有可能的字段

class MyResponse {

   int status; 
   public Map<String, APIMethod> result;    
}

class APIMethod {

    String description;
    String function;
    // etc
}
如果您确实想要一个
列表
,那么选项C将创建您自己的自定义反序列化程序,该反序列化程序将传递解析后的JSON,并创建一个包含
列表
的对象,而不是
映射
或POJO

class MyResponse {
    public int status;
    public List<APIMethod> methods;

    public MyResponse(int status, List<APIMethod> methods) {
        this.status = status;
        this.methods = methods;
    }
}


class MyDeserializer implements JsonDeserializer<MyResponse> {

    public MyResponse deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
    {
        Gson g = new Gson();
        List<APIMethod> list = new ArrayList<APIMethod>();
        JsonObject jo = je.getAsJsonObject();
        Set<Entry<String, JsonElement>> entrySet = jo.getAsJsonObject("result").entrySet();
        for (Entry<String, JsonElement> e : entrySet) {
            APIMethod m = g.fromJson(e.getValue(), APIMethod.class);
            list.add(m);
        }

        return new MyResponse(jo.getAsJsonPrimitive("status").getAsInt(), list);
    }
}

这很有帮助。谢谢
class Result {
    @SerializedName("auth.gettoken")
    APIMethod authGetToken;
    @SerializedName("blog.delete_post")
    APIMethod blogDeletePost;
    // etc
}
class MyResponse {
    public int status;
    public List<APIMethod> methods;

    public MyResponse(int status, List<APIMethod> methods) {
        this.status = status;
        this.methods = methods;
    }
}


class MyDeserializer implements JsonDeserializer<MyResponse> {

    public MyResponse deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
    {
        Gson g = new Gson();
        List<APIMethod> list = new ArrayList<APIMethod>();
        JsonObject jo = je.getAsJsonObject();
        Set<Entry<String, JsonElement>> entrySet = jo.getAsJsonObject("result").entrySet();
        for (Entry<String, JsonElement> e : entrySet) {
            APIMethod m = g.fromJson(e.getValue(), APIMethod.class);
            list.add(m);
        }

        return new MyResponse(jo.getAsJsonPrimitive("status").getAsInt(), list);
    }
}
Gson gson = new GsonBuilder()
                .registerTypeAdapter(MyResponse.class, new MyDeserializer())
                .create();