Reputation: 53
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"
}
Upvotes: 5
Views: 1944
Reputation: 321
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!!!
Upvotes: 1
Reputation: 262474
I think you can annotate like
@XmlElement(name="posted_by")
private String postedBy;
Upvotes: 1