Nov 23, 2010

JSON to java object, Java object to JSON

Using the ObjectMapper from Codehaus to convert java object into json and the opposite direction, from json to java object.
Java object to JSON, code example:
OutputStream outputStream = new ByteArrayOutputStream();
new ObjectMapper().writeValue(outputStream , obj);
return outputStream .toString();
JSON to Java object, code example:
new ObjectMapper().readValue(jsonStr, Person.class);
1. Don't forget to handle exceptions that might occur when converting using the jackson mapper.
2. Consider using / creating the mapper once as static for wide application usage.
3. The code above is an example, exception handling needed in real code.
Good day,

No comments:

Post a Comment