Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use class name as root key for JSON Jackson serialization

Suppose I have a pojo:

import org.codehaus.jackson.map.*;  public class MyPojo {     int id;     public int getId()     { return this.id; }      public void setId(int id)     { this.id = id; }      public static void main(String[] args) throws Exception {         MyPojo mp = new MyPojo();         mp.setId(4);         ObjectMapper mapper = new ObjectMapper();         mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);         System.out.println(mapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.WRAP_ROOT_VALUE));         System.out.println(mapper.writeValueAsString(mp));     } } 

When I serialize using the Jackson ObjectMapper, I just get

true {"id":4} 

but I want

true {"MyPojo":{"id":4}} 

I've searched all over, Jacksons documentation is really unorganized and mostly out of date.

like image 570
DanInDC Avatar asked Mar 12 '10 20:03

DanInDC


People also ask

How do I ignore a root element in JSON?

How to ignore parent tag from json?? String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}"; And here is the class to be mapped from json. (a) Annotate you class as below @JsonRootName(value = "parent") public class RootWrapper { (b) It will only work if and only if ObjectMapper is asked to wrap.

How do you serialize an object to JSON Jackson in Java?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

What is ObjectMapper class in Jackson?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.

Can we use @JsonProperty at class level?

But as far as @JsonProperty goes, no, the POJO classes do NOT need anything to mark them as serializable; nor do properties if you have public getter or setter.


1 Answers

By adding the jackson annotation @JsonTypeInfo in class level you can have the expected output. i just added no-changes in your class.

package com.test.jackson;  import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig;  import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;  @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME) public class MyPojo {     // Remain same as you have } 

output:

{     "MyPojo": {         "id": 4     } } 
like image 178
Arun Prakash Avatar answered Sep 19 '22 04:09

Arun Prakash