Monday, July 9, 2012

Jackson: From Object to JSON String and Back

This is how it's done:
ObjectMapper jsonMapper = new ObjectMapper();
String jsonStr = jsonMapper.writeValueAsString(jsonObj);

And the other way round:
ObjectMapper jsonMapper = new ObjectMapper();
UserAccount result = jsonMapper.readValue(userAccountJson,  UserAccount.class);

2 comments:

  1. Personally I don't like automatic conversion to JSON, I prefer a IJSONIfyable interface with a toJSON method. Then a static library like JSONUtils.toJSON(Object x) that will jsonify depending on the type of x (and understands that IJSONifyable must call toJSON).

    ReplyDelete
  2. Some of these frameworks are actually pretty customizable, like the ability to selectively include/exclude fields. Anyway they're not a magic bullet. Convenient most times but you'll still have to do some low-level parsing from time to time.

    ReplyDelete