JacksonConverter和ObjectMapper用于嵌套对象

时间:2016-04-06 03:47:37

标签: android json retrofit objectmapper

我正在使用Retrofit和JacksonConverter从API获取JSON数据。

JSON响应是这样的: -

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

但在我的课程中我只想要父对象的id,名称和嵌套对象的名称

我有这门课: -

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

    @JsonProperty("name")
    String mName;

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

我不想为A中的嵌套对象创建另一个对象。我只想将嵌套对象的名称字段存储在A中。

上面的类不会抛出任何异常,但mNestedName将为空。

反正有没有得到这样的数据?我是否需要更改mNestedName的@JsonProperty。

这就是我声明我的Retrofit实例的方式

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;

我正在通过此获取数据: -

@GET("something/list/")
 Call<List<A>> getA(@Header("Authorization") String authorization);

1 个答案:

答案 0 :(得分:1)

我没有Retrofit的经验,但如果你的问题主要与杰克逊有关。如果需要,可以通过使用setter / getter重构A类并将setter参数更改为Generic Object来避免生成POJO。

@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");
        }
    }