Escaped double quotes in JSON string causing error while parsing - java

I am using GSON to convert the List(Map(String,String)) to json string and passing it to the front end through session. GSON is properly escaping the double qoutes with /" but the problem is coming while parsing the json string.
The JSON string generated is
[{"queueList": [{"Name": "Queue\"1\""}, {"Name": "Queue2"}, {"Name": "Queue3"}, {"Name": "Queue4"}]}]
Error I am getting in chrome while parsing is: "UnExpected Number"
Code I am using to parse is as below
$(document).ready(function () {
var menuItemsStr = '[{"queueList": [{"Name": "Queue\"1\""}, {"Name": "Queue2"}, {"Name": "Queue3"}, {"Name": "Queue4"}]}]';
var menuItems = $.parseJSON(menuItemsStr);
$.each(menuItems[0].queueList, function (idx, obj) {
var listItemHTML = $("#listItem").clone().html();
listItemHTML = listItemHTML.replace(/\#QN/g, obj.Name);
$("#list").append(listItemHTML);
});
});
Below is the fiddle link where above code is present with the issue
http://jsfiddle.net/vinaybvk/qvwL9246/2/
When the JSON string has \\" then above fiddle is working fine as expected.
Working escaped JSON string is below:
var menuItemsStr = '[{"queueList": [{"Name": "Queue\\"1\\""}, {"Name": "Queue2"}, {"Name": "Queue3"}, {"Name": "Queue4"}]}]';
I am not able to find a way to add \\ before " to get the behavior working. I am trying both in java and javascript.
what i am trying to do in javascript is there in the above fiddle in comments
what I am trying to do in java is str.replaceAll("\"", "\\\\\")); which is generating the string with \\\"
Please let me know Is there any way to get this corrected or I am doing something wrong.
Thanks.

Instead of quoting the string then parsing it, in this case you can just do:
var menuItems = <s:property value="#session['jsonFormattedResult']" escapeHtml = "false" />;
which results in a valid object.

Related

How to use replaceAll in java without removing the whitespaces?

I have json string like :
{
"type": "abc_onClick",
"selectedComponent": "xyz_Button",
"displayEventName": "On Click",
"eventCategory": "Component Events"
}
I am trying to replace "type": "abc_ with some other string which is working fine but I need to remove whitespaces first. This is how I am doing it :
json = json.replaceAll("\\s", "");
json = json.replaceAll("\"type\":\"abc_\", "\"type\":\"newName_\");
But while doing so my json structure is getting changed as it is removing all the white spaces and I need the whitespaces as earlier. It is getting changed to :
{
"type": "abc_onClick",
"selectedComponent": "xyz_Button",
"displayEventName": "OnClick",
"eventCategory": "ComponentEvents"
}
Is there anyway I can achieve it with removing the whitespaces .
Note : I cannot loop or use JsonObject as these are the constraints.
Thanks

JSON Response Value says Null Rest Assured

My JSON Response reads something like:
{
"_embedded":{
"contents": [
{
"data": 1234,
"success": true,
}
]
}
}
I am attempting to extract the the success message and data. However my console output keeps reading null.
Once extracting the Response here is my code that receives a Null response using Rest Assured:
String res = response.asString():
JsonPath js = new JsonPath(res);
String success = js.get("_embedded[0].contents[0].success");
String data = js.get("_embedded[0].contents[0].data");
System.out.println(success);
System.out.println(data);
My response for both success and data is null
From your JSON sample, it looks like _embedded is not a list. _embedded[0] might return null because there is no list named _embedded when you try to extract the success value using "_embedded[0].contents[0].success".
Extract the success value by using
js.get("$._embedded.contents[0].success");

VelocyPack VPackParser returns null _key from toJson method

I have the following document in a collection named test:
[
{
"_key": "2469",
"_id": "test/2469",
"_rev": "_Ujegqfu---",
"fieldName": "some value"
}
]
I'm retrieving this with the following two methods:
public Result helloWorldJson() {
ArangoDB db = new ArangoDB.Builder().user("<user>").password("<pass>").build();
VPackParser parser = new VPackParser() ;
VPackSlice slice = db.db("<db>").collection("test").getDocument("2469", VPackSlice.class);
String json = db.db("cms").collection("test").getDocument("2469", String.class);
return Results.text().render("{velocy: " + parser.toJson(slice, true) + ", json: " + json);
}
Which produces this output:
{velocy: {"_key":"2469","_id":null,"_rev":"_Ujegqfu---","fieldName":"some value"}, json: {"_key":"2469","_id":"test\/2469","_rev":"_Ujegqfu---","fieldName":"some value"}
Does the VPackParser leave the _id null on purpose or am I missing something?
The _id field in stored documents is from a special velocypack type which isn't supported by Json and inlcudes the collection-id, the document is stored in.
To correctly deserialize this field in the human readable "collection-name/document-key" the deserialization process needs to know the collection-name of the given collection-id. This is only possible if the process can call the database or the internal collection-cache of the java-driver. Only when you call getDocument(String,Type) or another API method the deserialization process has access to this. VPackParser is a standalone Velocypack<->Json parser which isn't able to resolve the field _id.
String json = db.db("cms").collection("test").getDocument("2469", String.class);
As in your call, when you set type to String the method toJson() on an instance of VPackParser is used which has access to the dabase and the collection-cache and so can correctly desialize the field _id when parsing the velocypack to json.
If you want to deserialize a Velocypack separately from an api call (with correct parsing of _id) you can use the class ArangoUtil which you get from the method util() on ArangoDB,ArangoDatabase or ArangoCollection.
VPackSlice slice = db.db("<db>").collection("test").getDocument("2469", VPackSlice.class);
String json = db.util().deserialize(slice, String.class);

Conversion of JSON to XML

I am converting JSON Values to XML. Instead of getting JSON properties as elements of XML I am getting "title":"source". The output I wanted is <title>source</title>. What is the mistake I am doing? I am writing this code in JavaScript function.
I am using x2js plugin for conversion and I have included it using script tag.
My code to convert dynatree to JSON and JSON to XML is:
var x2js = new X2JS();
var tree = $("#source").dynatree("getTree").toDict();
alert(" tree:"+tree);
var jsonObject = JSON.stringify(tree);//dynatree to JSON
alert(" jsonObject :"+jsonObject);
var xmlAsStr = x2js.json2xml_str( jsonObject );//JSON to XML
alert("xml "+xmlAsStr);
Try to not use JSON.stringify(tree); this escapes the string.
Set var xmlAsStr = x2js.json2xml_str(tree);

JavaScript which inside JSP doesn't work when I used java tag

$( document ).ready(function() {
console.log( "ready!" );
var ilceler = "${ilceler}";
});
It doesn't print "Ready!" to console. When I debug with chrome, I saw
$( document ).ready(function() {
console.log( "ready!" );
var subChildList = "";
ilceler = JSON.parse(" [
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"},
{"id":"x","tag":"xx","name":"xxx xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xx\/xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"}]");
});
My data is true, but why this function doesn't work.
Note: My data includes UTF-8 characters.
Note2: I can work with string instead of json.
var a = ${tag}
console.log(a) >> "It's my tag"
I seems to me that you need to remove the quotes surrounding your variable.
So it should be
var ilceler = ${ilceler};
The JSP/JSTL interpreter will leave these quotes and hence your object will be regarded as a String value instead of a JSON object. Also if your second output is the output in the browser you can see it's not valid JSON.

Categories

Resources