Sha
Sha

Reputation: 1181

Gson return null for the nested-object

Actually, I try to implement so basic thing on my code. I have a json file. Then I want to read this json file and convert it to a Java object. To handle it, I used gson but somehow it returns null for nested-object.

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

and finally I try to read it from the json file:

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

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

But at the end of it, when I try to reach the System.out.println(resultJson.getResults().getAdsResult()); it gives null. Any suggestion?

Upvotes: 0

Views: 553

Answers (1)

pirho
pirho

Reputation: 12215

You are mixing Jackson and Gson annotations.

Make this change:

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

Upvotes: 1

Related Questions