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:
- Ignore the outer curly brackets ("
{" and "}") altogether - Change the
fruitto aWidget - Ignore the
statusaltogether
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.
weigtha string in your JSON but a double in your POJO? - fge