【问题标题】:How to map json response to pojo如何将json响应映射到pojo
【发布时间】:2014-04-12 03:21:05
【问题描述】:

我应该怎么做才能使用 GSON lib 将 json 响应转换为 object(pojo)?我收到了来自网络服务的回复:

{"responce":{"Result":"error","Message":"description"}}

并创建 POJO

public class ErrorResponse {

    private String result;
    private String message;
}

但是

ErrorResponse errorResponse = (ErrorResponse) gson.fromJson(new String(responseBody), ErrorResponse.class);

得到一个错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 应为字符串,但在第 1 行第 14 列是 BEGIN_OBJECT

更新

好的,我创建了

public class Wrapper {
    @SerializedName("Responce")
    private ErrorResponse response;
// get set
}


public class ErrorResponse {
    @SerializedName("Result")
    private String result;
    @SerializedName("Message")
    private String message;
// get set


 Wrapper wrapper = (Wrapper) gson.fromJson(new String(responseBody), Wrapper.class);
                        ErrorResponse errorResponse = wrapper.getResponse();

最后我得到 NPE errorResponse

【问题讨论】:

    标签: java android json mapping gson


    【解决方案1】:

    您的 JSON 实际上是一个 JSON 对象,其中包含一个名为 response 的 JSON 对象。该 JSON 对象具有您的 Pojo 的格式。

    所以一种选择是在 Java 中创建该层次结构

    public class Wrapper {
        private ErrorResponse response;
        // getters & setters
    }
    

    然后反序列化

    Wrapper wrapper = (Wrapper) gson.fromJson(new String(responseBody), Wrapper.class);
    ErrorResponse errorResponse = wrapper.getResponse();
    

    另一种方法是将 JSON 解析为 JsonElement,用于获取名为 response 的 JSON 对象并将其转换。使用 Gson 库中的以下类型:

    import com.google.gson.JsonParser;
    import com.google.gson.GsonBuilder;
    import com.google.gson.Gson;
    import com.google.gson.JsonElement;
    //...
    
    Gson gson = new GsonBuilder().create();
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(json);
    ErrorResponse response = gson.fromJson(jsonElement.getAsJsonObject().get("response"), ErrorResponse.class);
    

    请注意,您的类的字段名称必须与 JSON 匹配,反之亦然。 resultResult。或者您可以使用@SerializedName 使其匹配

    @SerializedName("Response")
    private String response;
    

    【讨论】:

    • @Gorets 您的字段名称不匹配。 Responceresponce.
    • 错误:(27, 29) java: org.springframework.boot.json.JsonParser 是抽象的;无法实例化
    • @sapy 你没有使用正确的JsonParser。我的答案来自 Gson,而不是 Spring boot。
    • @sapy 从问题的上下文([...] using GSON lib)和我的答案中的代码来看应该很明显,但可以肯定。我不知道你为什么认为是春天......
    • 我是一名经验丰富的工程师。这对我来说并不明显。
    【解决方案2】:

    您可以使用jsonschema2pojo 在线 POJO 生成器在 GSON 库的帮助下从 JSON 文档或 JSON 模式生成 POJO 类。在“注释样式”部分中,选择 GSON。创建 zip 文件后,将其解压缩并将所有类添加到类路径中。 注意:您需要将 GSON jar 添加到您的项目中。

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2017-03-31
      • 2016-10-20
      • 1970-01-01
      相关资源
      最近更新 更多