我目前正致力于从RestExpress到Jersey框架的Rest服务迁移,我必须拥有与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 );
输出:
{
"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
}
我的要求是将属性名称格式设置为 postedBy 为 published_by 。所以预期结果如下。
{
"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"
}
答案 0 :(得分:3)
@JsonProperty("posted_by")
private String postedBy;
答案 1 :(得分:1)
我认为你可以像
一样注释@XmlElement(name="posted_by")
private String postedBy;
答案 2 :(得分:1)
有两种方法可以做到这一点 第一个是
从此处下载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字符串。
另一种方式是 对于此方法,您必须将getter和setter添加到模型类
import com.google.gson.JsonObject;
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("propertyname",announcementDTO.gettermethod1());
jsonObject.addProperty("propertyname",announcementDTO.gettermethod2());
String s =jsonObject.toString();
这里将是你最后的jsonised字符串。
快乐编码!!!