【问题标题】:Custom deserialization of List using Jackson, SpringBoot - not working使用 Jackson、SpringBoot 对 List 进行自定义反序列化 - 不起作用
【发布时间】:2021-05-29 02:27:49
【问题描述】:

我正在尝试对 List 进行自定义反序列化。我在网上遵循了一些我可以找到但无法成功的提示。

汽车类

public class Car {

    private String market;
    private String date;

    @JsonDeserialize(using = CustomDeserializer.class)
    private List<CarValue> cars;

CustomDeserializer.java

public class CustomDeserializer extends JsonDeserializer<List<CarValue>> {

    @Override
    public List<CarValue> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        List<CarValue> result = new ArrayList<CarValue>();
        for(JsonNode value : node) {
            //result.add(node.get("name"));
        }

        return result;
    }

}

我不确定如何从我的 CustomDeserializer 类返回想要的数据。

来自List&lt;QuoteValue&gt;我只想返回带有键name的数据。

我该怎么做?

【问题讨论】:

  • @JsonExclude?
  • 试过@JsonIgnore 仍然存在我想我需要在我的模型中解析它,但我不知道如何:/
  • 应该已经有一个 ObjectMapper bean,不需要实例化它docs.spring.io/spring-boot/docs/2.3.x/reference/htmlsingle/… 然后只需使用 Gson、Jackson 或 JSON-B 的任何功能,具体取决于您的情况配置了哪一个。
  • @Aivaras 我正在使用 Jackson,并且我在 Loader.java 类中创建了 ObjectMaper。但我必须在我的CarValue.class 中进行解析。那么如何从一个类中的 ObjectMapper 获取数据到另一个类呢?

标签: java json spring-boot deserialization


【解决方案1】:

这是我所拥有的一个例子。

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;

import java.util.List;

public class VoucherPartnerGiftCardOp {
  @Expose
  private int voucherPartnerGiftCardID;
  @Expose
  private int marchantID;


  public VoucherPartnerGiftCardOp() {
  }

  public int getVoucherPartnerGiftCardID() {
    return voucherPartnerGiftCardID;
  }

  public void setVoucherPartnerGiftCardID(int voucherPartnerGiftCardID) {
    this.voucherPartnerGiftCardID = voucherPartnerGiftCardID;
  }

  public int getMarchantID() {
    return marchantID;
  }

....

  public String toJson() {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
    return gson.toJson(this);
  }
}

【讨论】:

  • OP提到了Jackson的用法
猜你喜欢
  • 2016-03-14
  • 1970-01-01
  • 2020-04-11
  • 2020-12-08
  • 2020-11-28
  • 2014-08-02
  • 2013-10-10
  • 2017-03-02
  • 1970-01-01
相关资源
最近更新 更多