jackson 继承DRY响应

kq4fsx7k  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(113)

我有两个用于外部API响应类:
A类:

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class ClassA {

  private SubClass subClass;

  @Getter
  @Setter
  public static class SubClass {

    Integer total;
    Integer perPage;
    List<Data> dataList;

    @Getter
    @Setter
    public static class Data {

      private String field1;
      private String field2;
      private int field3;
    }
  }
}

B类:

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class ClassB {

  private SubClass subClass;

  @Getter
  @Setter
  public static class SubClass {

    Integer total;
    Integer perPage;
    List<Data> dataList;

    @Getter
    @Setter
    public static class Data {

      private String field1;
      private int field2;
      private Date field3;
    }
  }
}

使用ObjectMapper进行反序列化:

ClassA classA =
      mapper.readValue(bodyResponse, ClassA.class);

在使用继承并在以后使用反序列化时,消除这些类中重复代码的最佳方法是什么?

z31licg0

z31licg01#

你需要使根和子类通用。使用TypeReference来提供你期望的数据类。看下面的例子:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Date;
import java.util.List;

public class GenericDataApp {
    public static void main(String[] args) throws JsonProcessingException {
        JsonMapper mapper = JsonMapper.builder().build();
        String srcA = "{\"subClass\":{\"total\":1,\"dataList\":[{\"field2\":\"String value\"}]}}";
        RootClass<DataA> dataA = mapper.readValue(srcA, new TypeReference<RootClass<DataA>>() {
        });
        System.out.println(dataA.getSubClass());

        String srcB = "{\"subClass\":{\"total\":1,\"dataList\":[{\"field2\":12}]}}";
        RootClass<DataB> dataB = mapper.readValue(srcB, new TypeReference<RootClass<DataB>>() {
        });
        System.out.println(dataB.getSubClass());
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
class RootClass<T> {

    private SubClass<T> subClass;

    @Getter
    @Setter
    @ToString
    public static class SubClass<T> {

        Integer total;
        Integer perPage;
        List<T> dataList;
    }
}

@Getter
@Setter
@ToString
class DataA {

    private String field1;
    private String field2;
    private int field3;
}

@Getter
@Setter
@ToString
class DataB {

    private String field1;
    private int field2;
    private Date field3;
}

以上代码打印:

RootClass.SubClass(total=1, perPage=null, dataList=[DataA(field1=null, field2=String value, field3=0)])
RootClass.SubClass(total=1, perPage=null, dataList=[DataB(field1=null, field2=12, field3=null)])

相关问题