How to convert a Java object to a Json formatting attribute name

I am currently working with the migration of Rest services from a RestExpress environment to Jersey, where it should have the same result 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 before posted_by . Thus, the expected result 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"
}
+4
source share
3 answers
@JsonProperty("posted_by")
private String postedBy;
+2
source

I think you can comment on how

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

-

Jar http://mvnrepository.com/artifact/com.google.code.gson/gson/2.3.1 com.google.gson.Gson;

Gson gson=new Gson();
String s=gson.toJson(Your object);

s - json.

and another way for this method you will need to add getters and setters to the 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 last jsonised string.

Happy coding !!!

0
source

Source: https://habr.com/ru/post/1613451/


All Articles