【问题标题】:Gson return null for the nested-objectGson 为嵌套对象返回 null
【发布时间】:2021-07-07 09:43:10
【问题描述】:

实际上,我尝试在我的代码中实现如此基本的东西。我有一个 json 文件。然后我想读取这个 json 文件并将其转换为 Java 对象。为了处理它,我使用了 gson,但不知何故它为嵌套对象返回 null。

json:

{
  "results": {
    "ads-result": {
      "data": [
        {
          "id": "1"
        }
      ]
    }
  }
} 

TestJson:

@Getter
public class TestJson
{
    private ResultsData results;

    @Getter
    public static class ResultsData
    {
        @JsonProperty(value = "ads-result")
        private AdsResultData adsResult;
    }

    @Getter
    public static class AdsResultData
    {
        private List<AdApp> data;
    }

    @Getter
    public static class AdApp
    {
        private long id;
    }
}

最后我尝试从 json 文件中读取它:

public static TestJson getDefaultAdResult() throws Exception
{
    String json = IOUtils.toString(
            getResourceAsStream("test.json"), StandardCharsets.UTF_8);

    return new Gson().fromJson(json, TestJson.class);
}

但最后,当我尝试到达System.out.println(resultJson.getResults().getAdsResult()); 时,它给出了 null。有什么建议吗?

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    您正在混合 Jackson 和 Gson 注释。

    进行此更改:

    // @JsonProperty(value = "ads-result") - Jackson
    @SerializedName("ads-result") // Gson
    private AdsResultData adsResult;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多