5

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"
}

3 Answers 3

3
@JsonProperty("posted_by")
private String postedBy;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is working. But I was searching for more generic solution since I have few DTO objects
1

I think you can annotate like

@XmlElement(name="posted_by")
private String postedBy;

1 Comment

Thanks this is working. But I was searching for more generic solution since I have few DTO objects
1

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!!!

1 Comment

Thanks this is working. But I was searching for more generic solution since I have few DTO objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.