【问题标题】:How to ignore attribute when mapping to json from a text file to a Java object using Jackson? [duplicate]使用Jackson从文本文件到Java对象映射到json时如何忽略属性? [复制]
【发布时间】:2015-04-24 20:19:10
【问题描述】:

我有一个包含此文本的文本文件“input.txt”

{
  "product" : {
    "name" : "Pro-1",
    "category" : "A"
  }
}

还有一个班级

public class  Product {
    @JsonProperty("name")
    public String name;
    @JsonProperty("category")
    public String category
    ...
    ...
}

我正在使用杰克逊

Product p = mapper.readValue(new File("input.txt"), Product.class);

我的类没有名为“product”的属性,因此在将 json 文本映射到产品对象时发生异常。那么,从文本文件映射到 Product 对象时,忽略此“产品”属性的正确方法是什么?

【问题讨论】:

标签: java json jackson


【解决方案1】:

试试这样的。

public class OuterClass{
    @JsonProperty("product")
    public Product product;
}

OuterClass outerObject = mapper.readValue(new File("input.txt"), OuterClass.class);

那你就可以用了outerObject.product

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2018-01-23
    • 1970-01-01
    相关资源
    最近更新 更多