在java中将对象转换为字符串并排除不必要的字符

时间:2014-09-03 10:27:32

标签: java json

我从一个java对象创建Json并将其转换为字符串格式此代码

new JSONObject(responseDTO.getDTOHeader()).toString();

但带有意外字符的字符串的结果。例如

"{\"languageID\":0,\"test1\":14,\"loginID\":\"LKS280\",\"errorCategory\":0,\"replyTopic\":null,\"errorCode\":0,\"sessionType\":null,\"sessionKey\":\"LKS2801409739957847\",\"creationTime\":\"Wed Sep 03 15:55:57 IST 2014\",\"messageType\":3,\"version\":\"1.0.0\"}

如何排除\“

1 个答案:

答案 0 :(得分:0)

使用Json.parse()在客户端处理它。

Java String作为JavaScript String,然后parse传递给客户端String

var str="{\"languageID\":0,\"test1\":14,\"loginID\":\"LKS280\",\"errorCategory\":0,\"replyTopic\":null,\"errorCode\":0,\"sessionType\":null,\"sessionKey\":\"LKS2801409739957847\",\"creationTime\":\"Wed Sep 03 15:55:57 IST 2014\",\"messageType\":3,\"version\":\"1.0.0\"}";

var obj=JSON.parse(str);  //parse string to json 

这是演示小提琴http://jsfiddle.net/vikrant47/e26t6LjL/

替换所有\ whith ""

new JSONObject(responseDTO.getDTOHeader()).toString().replaceAll("\\","");