1

I have code like this:

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.writeValueAsString(mp));
    }
}

It works expected:

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

But I want to customize that name. I am not able to mark MyPojo with @JsonTypeInfo becausee i take this class from library.

Is there way to do it in jackson?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

2

You can use ObjectWriter also specifically for this class:

MyPojo mp = new MyPojo();
mp.setId(4);
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer().withRootName("TestPojo");
System.out.println(writer.writeValueAsString(mp));
Sukhpal Singh
  • 2,130
  • 9
  • 20
0

Instead of using SerializationConfig.Feature.WRAP_ROOT_VALUE you could just create a new class like this:

public class MyWrapper {

    private MyPojo myName = new MyPojo();

    public void setId(int id) { myName.setId(id); }
}

If you create a JSON out of an object of this type, the attribute will have the name myName, e.g.: {"myName" : {"id" : 4} }.

markusw
  • 1,975
  • 16
  • 28