how to handle '\' in json string - json

In my json message the field which should have one '\' comes with '\\'
In the below example
"validation": "^[^\\s][a-zA-Z\\(\\) ,.-]+[^\\s]$"
Should come as
"validation": "^[^\s][a-zA-Z\(\) ,.-]+[^\s]$",
I am not getting why it is happening like this. Any one out there to help me.
"getTransactionDataRequirementsResponse": {
"return": [
{
"errorMessage": "Cannot start or end with whitespace",
"validation": "^[^\\s][a-zA-Z\\(\\) ,.-]+[^\\s]$",
},
{
"errorMessage": "Cannot start or end with whitespace",
"validation": "^[^\\s][a-zA-Z\\(\\) ,.-]+[^\\s]$",
},
}
No way I could pass an odd number of backslashes through json. Below is one test code
String jsonString = "{\"validation\" : \" 1\\ 2\\\\ 3\\\\\\ 4\\\\\\\\\ 3\\\" }";
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(jsonString);
JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println("validation=" + jsonObject.get("validation"));
Output comes as below
validation=" 1 2\ 3\ 4\\"

When you encode data to JSON format all special chars are escapes (e.g. '/' => '//'). And if you want to use JSON data, decodes them using the parseJSON() method.

Related

org.json.JSONException: Expected literal value at character 85

This is my json string :
{
gateway=vary,
gateway_text=xyz,
gateway_data=,
start=17/02/2022 06:23:45,
end=17/03/2022 06:23:45,
promo_time=17/03/2022 06:23:45,
in_process_canceled=0.0,
id=817957632
}
When I am trying to convert it to JSON object, it is throwing the exception
val obj = JSONObject(purchaseData.toString())
Please help me resolve this.
Your json is not a valid json, remove "=" and put double quotes in property and values
{
"gateway": "vary",
"gateway_text": "xyz",
"gateway_data": "ss",
"start": "17/02/202206:23:45",
"end": "17/03/202206:23:45",
"promo_time": "17/03/202206:23:45",
"in_process_canceled": "0.0",
"id": "817957632"
}
Then it will work
This can handled by converting it to a json string ;
json = json.replace(" ","")
json = json.replace("\n","")
json = json.replace("{", "{\"")
json = json.replace("}", "\"}")
json = json.replace("=", "\":\"")
json = json.replace(",", "\",\"")
val obj = JSONObject(json)

Accessing JSON response

I am storing the response of a REST Get request and trying to access as below,
final JSONObject receivedItem = new JSONObject(response.readEntity(String.class));
This is the sample response,
[
{
"timeStamp": 1511136000000,
"contextKeys": [
{
"tKey": "Test1",
"contextKey": "Location",
"contextValue": "San Jose",
"eCount": 3
},
{
"tKey": "Test1",
"contextKey": "Name",
"contextValue": "User1",
"eCount": 3
}
}
]
And i am getting the below error,
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
Any clues ?
Thanks
As Rajkumar pointed out, in your example there is a missing close bracket - but this may just be a simple typing error.
The actual error message is saying A JSONObject text must begin with '{' which is because JSON objects are exactly that, objects. You need to use a JSONArray to parse your example JSON as follows:
final JSONArray receivedItem = new JSONArray(response.readEntity(String.class));
This may change some of your other code to handle this as an array vs an object.
If your problem is with storing and accessing json response try this response instead;
I am presuming that you are using javascript; Anyways, core idea is the same;
var jsonStorage;
$.getJSON('your url',(json) => {
jsonStorage = json;
});
console.log(jsonStorage) //your jsonresponse is now available here;

Escaping JSON Payload with back slash

I have an external service that returns a JSON Payload as below
{
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
}
How could I escape the back slash? I need to use a json path and currently I cant do it. Is there a better way than String Replace? Thanks.
Regards,
Hari
Just simply parse your JSON string. like that.
var response = {
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
};
var result = $.parseJSON(response.GetIPAResult);
Now you can get your data (in result variable) without back slash.
hari .. at a moment your json structure are as follows
{"key": "value"}
where value is a stringify of {"Data" : JSONARRAY}
here 2 case arise..
case 1:
try to change the structure of return json to
{"key": JSONOBJECT}
where JSONOBJECT -> {"DATA": JSONARRAY}
case 2:
try to convert return json to
{"key": JSONOBJECT}
where JSONOBJECT -> {"DATA": JSONARRAY}
by replace "{ with { , \" with " and }" with }
hence the result of
{
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
}
to
{
"GetIPAResult": {"Data":[{"Name":"Pan1","Email":"abc#example.com"},{"Name":"Pan2","Email":"xyz#example.com"}]}
}

Use a JSON with JSONOBJECT in Java

I want to use the following JSON in my code in Java:
[
{
"speed": 200
}
]
I tried to write this line :
JSONObject jsonBody = new JSONObject("[{\"speed\": 200}]");
But I always get an error. What is the exact format that I have to use here??
EDIT: So it would be more proper to use a JSONArray rather than use a JSONObject (as my last post said)
So the correct java code would be
String json = "[{\"speed\": 200}]";
System.out.println(json);
JSONArray jsonBody = new JSONArray(json);
System.out.println(jsonBody.getJSONObject(0).get("speed"));

Grails: Parsing through JSON String using JSONArray/JSONObject

I have the below JSON string coming in as a request parameter into my grails controller.
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
As you can see, the timesheetList might have multiple elements in it. In this ( above ) case, we have only one. So, I expect it to behave like an Array/List.
Then I had the below code to parse through it:
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def timesheet1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now. Any help?
1st off to simplify your code, use request.JSON. Then request.JSON.list[ 0 ] should be working