Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jackson to deserialize JSON objects to POJOs

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.

like image 905
csaunders Avatar asked Dec 06 '25 13:12

csaunders


1 Answers

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.

like image 91
StaxMan Avatar answered Dec 09 '25 03:12

StaxMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!