-1

I WANT TO SERIALIZE WITH CUSTOM NAME DONT CLASS NAME

I alreay know about this. Pls dont refer to this answer.

How to Serialize pojo class name with jackson. Example:

public class A{
private int a;
//getter seeter
}

when serialize A want to be like:

{"a": 1,"class":"ARequest"}

how to serialize Pojo with given className. Is it possible without override toString() method .I used this class in retrofit Post method body.

One point i dont serialize it under class name like:

{"ARequest":{"a":5}}
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39

2 Answers2

1

Annotate your class with @JsonTypeInfo:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="class")
public class Foo {

    public String bar;

    // Getters and setters
}

Then consider the following code:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(foo));

It will produce the following output:

{
  "class" : "Foo",
  "bar" : "test"
}

If you want the full qualified name of the class, such as org.example.Foo, you can use JsonTypeInfo.Id.CLASS instead of JsonTypeInfo.Id.NAME.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
1

You can use @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="class") as described here

Halko Karr-Sajtarevic
  • 2,248
  • 1
  • 16
  • 14