2015-10-28 94 views
4

我目前正在从RestExpress Rest服务迁移到Jersey框架,我必须具有与RestExpress相同的输出。如何将Java对象转换为Json格式属性名称

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属性名称为posted_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" 
} 

回答

2
@JsonProperty("posted_by") 
private String postedBy; 
+0

感谢这是工作。但我正在寻找更通用的解决方案,因为我有几个DTO对象 –

0

我觉得你可以注解像

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

谢谢你的工作。但我正在寻找更通用的解决方案,因为我有几个DTO对象 –

0

有两种方法可以做到这一点 第一个是从这里

下载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字符串。

快乐编码!

+0

谢谢你的工作。但我正在寻找更通用的解决方案,因为我有几个DTO对象 –

+0

接受答案。 –

相关问题