使用 Jackson 将 JSON 对象反序列化为 POJO
我正在尝试通过 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"}
我也遇到了同样的问题。
I'm trying to use Jackson in an Android project via the ObjectMapper.
My POJO is as follows:
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; }
}
I've written up a Unit Test to see if I could get Jackson working to deserialize my JSON objects.
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());
}
My actual JSON file contains much more information than what I've set in my Product, but I just want to get it working. Using the larger file it causes the Product to get created but all it's values are set to null. I thought this might be because of all the data that is in there, so I created another file (foo.json) that contains the following:
{"title" : "Macbook", "vendor" : "Apple"}
With which I am also getting the same problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,您不需要这些 @JsonProperty 注释,因为您有隐含“标题”的 getter 和 setter(根据 bean 命名约定)。无论哪种方式,代码都应该像您所示的那样工作。
我可能会首先验证 ctxt.getAssets().open() 不返回空内容?这是唯一突出的事情。
Note that you do not need those @JsonProperty annotations, since you have getters and setters which imply "title" (as per bean naming convention). Either way, code should work as you have shown.
I would probably verify first that ctxt.getAssets().open() does not return empty content? That's about the only thing that stands out.