Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JacksonConverter and ObjectMapper for nested objects

I am using Retrofit and JacksonConverter to fetch JSON data from an API.

The JSON response is like this:-

[
  {
    "id": 163,
    "name": "Some name",
    "nested": {
      "id": 5,
      "name": "Nested Name",
      }
  }
]

But in my class I only want the id, name of the parent object and the name of the nested object

I have this class :-

@JsonIgnoreProperties(ignoreUnknown = true)
class A{
    @JsonProperty("id")
    int mId;

    @JsonProperty("name")
    String mName;

    @JsonProperty("nested/name")
    String mNestedName;
}

I don't want to create another object for the nested object inside A. I just want to store the name field of the nested object in A.

The above class doesn't throw any exceptions but the mNestedName will be empty.

Is there anyway to do get the data like this? Do I need to change the @JsonProperty for mNestedName.

This is how I have declared my Retrofit instance

ObjectMapper mapper = new ObjectMapper();
       mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(JacksonConverterFactory.create())
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;

And I am getting the data through this:-

@GET("something/list/")
 Call<List<A>> getA(@Header("Authorization") String authorization);
like image 842
Abhinav Nair Avatar asked Jun 20 '26 08:06

Abhinav Nair


1 Answers

I don't have experience on Retrofit but if your problem is mostly related to Jackson. You can avoid generating POJO if you want by refactoring your A class with setter/getter and changing the setter param to Generic Object.

@JsonIgnoreProperties(ignoreUnknown = true)
public static class A{
    @JsonProperty("id")
    int mId;

    @JsonProperty("name")
    String mName;


    @JsonIgnoreProperties
    String mNestedName;

    public String getmNestedName() {
        return mNestedName;
    }

    @JsonProperty("nested")
    public void setmNestedName(Object mNestedName) {
        if(mNestedName instanceof Map) {
            this.mNestedName = (String)((Map)mNestedName).get("name");
        }
    }
like image 142
Baski Avatar answered Jun 21 '26 23:06

Baski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!