使用Jackson将JSON对象反序列化为POJOs

3

我正在尝试通过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文件包含比我在Product中设置的更多信息,但我只想让它工作。 使用更大的文件会导致创建Product,但所有值都设置为null。 我认为这可能是因为其中的所有数据,因此我创建了另一个文件(foo.json),其中包含以下内容:

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

我也遇到了同样的问题。


你使用的是哪个版本的Jackson?@JsonProperty只允许在1.0版本之后作为字段注释。 - nicholas.hauschild
jackson-(core/mapper)-asl-1.6.4 - csaunders
1个回答

1
请注意,您不需要那些@JsonProperty注释,因为您有getter和setter,这意味着“title”(根据bean命名约定)。无论哪种方式,代码应该像您展示的那样工作。
我可能会先验证ctxt.getAssets().open()是否返回空内容?这是唯一引人注目的事情。

我意识到我在运行哪些测试方面犯了一些错误,这是混淆的主要原因。我会将您的评论标记为正确,因为它确实澄清了jackson注释的正确用法。 - csaunders

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接