I'm currently working on Rest service migration from RestExpress to Jersey framework where I have to have the same output as RestExpress.
public class AnnouncementDTO {
private String id;
private String title;
private String details;
private String postedBy;
private String permanent;
private String dismissible;
private String startDate;
private String endDate;
}
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(announcementDTO );
Output:
{
"id" : null,
"title" : "<font size=\"3\" color=\"red\">This is some text!</font>",
"details" : "<p>fhmdhd</p>",
"postedBy" : "Portal, Administrator",
"permanent" : null,
"dismissible" : null,
"startDate" : "Jul 19, 2014, 04:44 AM IST",
"endDate" : null,
"read" : null
}
My requirement is to format attribute names as postedBy to posted_by. So expected outcome will be as follows.
{
"title":"<font size=\"3\" color=\"red\">This is some text!</font>",
"details":"<p>fhmdhd</p>",
"posted_by":"Portal, Administrator",
"start_date":"Jul 19, 2014, 04:44 AM ET"
}
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.
In order to change the field name, we use the @JsonProperty annotation. In the annotation constructor, we pass the name of the property. Let's take an example to understand how we can use @JsonProperty annotation to change the name of the field for serialization.
There are two parameters in the fromJson() method, the first parameter is JSON String which we want to parse and the second parameter is Java class to parse JSON string. We can pass one parameter into the toJson() method is the Java object which we want to convert into a JSON string.
@JsonProperty("posted_by")
private String postedBy;
I think you can annotate like
@XmlElement(name="posted_by")
private String postedBy;
There are two ways to do so The first one is
Download Jar from here and add to your class path http://mvnrepository.com/artifact/com.google.code.gson/gson/2.3.1 and then import com.google.gson.Gson;
Gson gson=new Gson();
String s=gson.toJson(Your object);
s is your json string.
and the other way is for this method you will have to add getters and setters to your model class
import com.google.gson.JsonObject;
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("propertyname",announcementDTO.gettermethod1());
jsonObject.addProperty("propertyname",announcementDTO.gettermethod2());
String s =jsonObject.toString();
here s will be your final jsonised string.
Happy Coding!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With