如何将Java对象转换为Json格式属性名
我目前正在进行Rest服务从RestExpress迁移到Jersey框架的工作,在Jersey框架中,我必须具有与RestExpress相同的输出如何将Java对象转换为Json格式属性名,java,json,Java,Json,我目前正在进行Rest服务从RestExpress迁移到Jersey框架的工作,在Jersey框架中,我必须具有与RestExpress相同的输出 public class AnnouncementDTO { private String id; private String title; private String details; private String postedBy; private String permanent; pri
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
}
{
“id”:空,
“标题”:“这是一些文字!”,
“详情”:“fhmdhd”,
“postedBy”:“门户,管理员”,
“永久”:空,
“可驳回”:空,
“起始日期”:“2014年7月19日凌晨4:44 IST”,
“endDate”:空,
“读取”:空
}
我的要求是将属性名称格式化为postedBy到postedBy。因此,预期结果如下
{
"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"
}
{
“标题”:“这是一些文字!”,
“详情”:“fhmdhd”,
“发布人”:“门户,管理员”,
“开始日期”:“美国东部时间2014年7月19日凌晨04:44”
}
我想你可以这样注释
@XmlElement(name="posted_by")
private String postedBy;
有两种方法可以做到这一点 第一个是 从这里下载Jar并添加到您的类路径 然后导入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字符串
快乐编码 谢谢,这很有效。但我一直在寻找更通用的解决方案,因为我几乎没有什么数据对象,这是可行的。但我一直在寻找更通用的解决方案,因为我几乎没有什么数据对象,这是可行的。但我一直在寻找更通用的解决方案,因为我几乎没有DTO对象
import com.google.gson.JsonObject;
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("propertyname",announcementDTO.gettermethod1());
jsonObject.addProperty("propertyname",announcementDTO.gettermethod2());
String s =jsonObject.toString();