3

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);
Abhinav Nair
  • 958
  • 1
  • 8
  • 29
  • why dont you want to define another class for the nested json? thats the simplest solution here. – Hector Apr 06 '16 at 03:53
  • @Hector The nested class has lot of fields and I just need that one particular field. Moreover I will be saving class A in SQLite database. So if I use the nested object, then I would have to save that too in the database with relationships between them. This would mean a lot of unnecessary overhead. – Abhinav Nair Apr 06 '16 at 04:01

1 Answers1

1

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");
        }
    }
Baski
  • 829
  • 8
  • 14