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.
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.