【问题标题】:Using Jackson to deserialize JSON objects to POJOs使用 Jackson 将 JSON 对象反序列化为 POJO
【发布时间】:2011-01-26 17:33:54
【问题描述】:

我正在尝试通过 ObjectMapper 在 Android 项目中使用 Jackson。

我的POJO如下:

public class Product {
    @JsonProperty("title")
    String title;
    @JsonProperty("vendor")
    String vendor;

    public void setTitle(String title){ this.title = title; }
    public void setVendor(String vendor){ this.vendor = vendor; }

    public String getTitle() { return title; }
    public String getVendor() { return vendor; }
}

我编写了一个单元测试,看看是否可以让 Jackson 反序列化我的 JSON 对象。

Context ctx;

public void setUp() throws Exception {
    super.setUp();
    ctx = getContext();
}

public void testConvertJSONToProduct() throws Exception {
    ObjectMapper m = new ObjectMapper();
    Product product = m.readValue(ctx.getAssets().open("foo.json"), Product.class);

    assertEquals("Macbook", product.getTitle());
}

我的实际 JSON 文件包含的信息比我在产品中设置的信息多得多,但我只想让它工作。使用较大的文件会导致创建产品,但它的所有值都设置为空。我认为这可能是因为那里的所有数据,所以我创建了另一个文件(foo.json),其中包含以下内容:

{"title" : "Macbook", "vendor" : "Apple"}

我也遇到了同样的问题。

【问题讨论】:

  • 您使用的是哪个版本的 Jackson? @JsonProperty 仅允许在 1.0 版本之后作为字段注解。
  • jackson-(core/mapper)-asl-1.6.4

标签: android json jackson


【解决方案1】:

请注意,您不需要那些 @JsonProperty 注释,因为您有隐含“标题”的 getter 和 setter(根据 bean 命名约定)。无论哪种方式,代码都应该像你展示的那样工作。

我可能会首先验证 ctxt.getAssets().open() 不会返回空内容?这是唯一突出的地方。

【讨论】:

  • 我意识到我在运行测试时犯了一些错误,这是造成混乱的主要原因。我会将您的评论标记为正确,因为它确实阐明了杰克逊注释的正确用法。
猜你喜欢
  • 2012-04-07
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2020-12-10
  • 2023-03-13
相关资源
最近更新 更多