convert java Object to JSON String

1) Object to String

String json = objectMapper.writeValueAsString(objectA);

Useful method

<T> T objectMapper.convertValue(Object fromValue (i.e. String), Class<T> destinationClass)

Example String x = objectMapper.convertValue(“test”, String.class);

JsonNode j = mapper.convertValue(object, JsonNode.class);

ObjectA Example

class ObjectA{

public WhatEver ignoreThis(){



String getCurrentTime(){
return new SimpleDateFormat(&quot;yyyy-MM-dd&quot;).format(new Date());


Another annotation to use with @JsonProperty is @JsonView
i.e. @JsonView({PublicView.class, AnotherView.class})

2) String to JsonNode

JsonNode jsonNode = objectMapper.readTree(string);
Iterator&amp;lt;Entry&amp;lt;String, JsonNode&amp;gt;&amp;gt; fields = jsonNode.fields();
while (fields.hasNext()) {
Entry&amp;lt;String, JsonNode&amp;gt; field =;
JsonNode value = field.getValue();
// field.getKey(), value.textValue()

Useful method



jsonNode.textValue(), jsonNode.toString()

T t = objMapper.readValue(jsonNode.traverse(), String.class);

public <T> T readValue(InputStream src, WhateverClass.class);

3) create node

ObjectNode objNode = objectMapper.createObjectNode();

objNode.put('key', jsonNode);

or we can use org.json.JSONObject.JSONObject

JSONObject jo = new JSONObject(str);
String val = jo.getString(key);
JSONObject o = jo.getJSONObject(key);
Boolean b = jo.getBoolean(key);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s