IAmYourFaja
IAmYourFaja

Reputation: 56944

Mapping JSON back to POJO with JSON and Jackson libs

I have a JSON string:

{
    "fruit": {
        "weight":"29.01",
        "texture":null
    },
    "status":"ok"
}

...that I am trying to map back into a POJO:

public class Widget {
    private double weight; // same as the weight item above
    private String texture; // same as the texture item above

    // Getters and setters for both properties
}

The string above (that I am trying to map) is actually contained inside an org.json.JSONObject and can be obtained by calling that object's toString() method.

I would like to use the Jackson JSON object/JSON mapping framework to do this mapping, and so far this is my best attempt:

try {
    // Contains the above string
    JSONObject jsonObj = getJSONObject();

    ObjectMapper mapper = new ObjectMapper();
    Widget w = mapper.readValue(jsonObj.toString(), Widget.class);

    System.out.println("w.weight = " + w.getWeight());
} catch(Throwable throwable) {
    System.out.println(throwable.getMessage());
}

Unfortunately this code throws an exception when the Jackson readValue(...) method gets executed:

Unrecognized field "fruit" (class org.me.myapp.Widget), not marked as ignorable (2 known properties: , "weight", "texture"])
    at [Source: java.io.StringReader@26c623af; line: 1, column: 14] (through reference chain: org.me.myapp.Widget["fruit"])

I need the mapper to:

  1. Ignore the outer curly brackets ("{" and "}") altogether
  2. Change the fruit to a Widget
  3. Ignore the status altogether

If the only way to do this is to call the JSONObject's toString() method, then so be it. But I'm wondering if Jackson comes with anything "out of the box" that already works with the Java JSON library?

Either way, writing the Jackson mapper is my main problem. Can anyone spot where I'm going wrong? Thanks in advance.

Upvotes: 2

Views: 19336

Answers (1)

Srinivas
Srinivas

Reputation: 1790

You need to have a class PojoClass which contains (has-a) Widget instance called fruit.

Try this in your mapper:

    String str = "{\"fruit\": {\"weight\":\"29.01\", \"texture\":null}, \"status\":\"ok\"}";
    JSONObject jsonObj = JSONObject.fromObject(str);
    try
    {
        // Contains the above string

        ObjectMapper mapper = new ObjectMapper();
        PojoClass p = mapper.readValue(jsonObj.toString(), new TypeReference<PojoClass>()
        {
        });

        System.out.println("w.weight = " + p.getFruit().getWeight());
    }
    catch (Throwable throwable)
    {
        System.out.println(throwable.getMessage());
    }

This is your Widget Class.

public class Widget
{    private double weight;
     private String texture;
    //getter and setters.
}

This is your PojoClass

public class PojoClass
{
    private Widget fruit;
    private String status;
    //getter and setters.
}

Upvotes: 5

Related Questions