0

I am returning a dataset from database in List and converting them into a JSON as below.

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.

[
    {"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)

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

2. I need the following format. The extra quotes before [ is making my dataTable a mess-up.

{
    "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. Please help me.

EDIT : Adding screenshots from Browser Console: Working JSON

Not working JSON

1
  • You seem to have to fix the way your JSON is written to the output stream (just don't use serialization to string). Commented Apr 22, 2017 at 14:53

1 Answer 1

1

This should work, if you're happy doing it within your 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.

Sign up to request clarification or add additional context in comments.

5 Comments

Do you know why this happening ? I have printed this JSON in java class it was correct but the same was showing incorrect when I am seeing it in browser console. Really strange.
Nope, not without some more information about your setup. I just took what you provided and made it work :-)
I have edited the question with screenshots that has the json. The problem is with the array structure I think, Can you please looks at the images and advise.
Any idea on this please ?
It looks as though you're using Java to populate your data using Google's gson class...? Should that be the case then I think something is going on there. If you output everything other than the 'data' does it work or produce valid json? I'd suggest that might be the case and that you perhaps need to do the generation of json as a two step process... jsonify your data and then add wrappers with 'data:'. Otherwise I'm not sure how to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.