简体   繁体   English

使用Gson的JSON格式

[英]JSON format using Gson

I am returning a dataset from database in List and converting them into a JSON as below. 我从列表中的数据库返回一个数据集,并将它们转换为JSON,如下所示。

List<DensityGroup> dg = pdao.getProductPropListData("Density");
String data = new Gson().toJson(dg);
System.out.println(data);

I am facing below problems: 我面临以下问题:

1. System.out is printing the following in console. 1. System.out在控制台中打印以下内容。

[
    {"densityId":"11","densityDescription":"Mcvr"},
    {"densityId":"14","densityDescription":"test"}
]

I am getting the below response into browser with escape characters (I am making an AJAX call) 我在浏览器中收到以下带有转义符的响应(我正在进行AJAX调用)

{"data":"[{\"densityId\":\"11\",\"densityDescription\":\"Mcvr\"},{\"densityId\":\"14\",\"densityDescription\":\"test\"}]"}

2. I need the following format. 2.我需要以下格式。 The extra quotes before [ is making my dataTable a mess-up. [之前的多余引号使我的dataTable变得一团糟。

{
    "data": [
        {"densityId":"11","densityDescription":"Mcvr"},
        {"densityId":"14","densityDescription":"test"}
    ]
}

3. I don't need the escaping quotes before every double quotes in my current output. 3.在当前输出中的每个双引号之前,我不需要转义引号。 Please help me. 请帮我。

EDIT : Adding screenshots from Browser Console: 编辑 :从浏览器控制台添加屏幕截图: 工作JSON

无法使用JSON

This should work, if you're happy doing it within your Javascript: 如果您很高兴在Javascript中执行此操作,则应该可以使用:

var str = {"data":"[{\"densityId\":\"11\",\"densityDescription\":\"Mcvr\"},{\"densityId\":\"14\",\"densityDescription\":\"test\"}]"}

var data = JSON.parse(JSON.stringify(str).replace(/\\\"/g, '"').replace(/\"\[/g, '[').replace(/\]\"/g, ']'));

console.log(data);

It should work, but it might be better to fix it as it's coming from your server instead. 它应该可以工作,但是最好修复它,因为它来自服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM