My JSON string looks like this. Please note that it has escape characters.
string json = "\"{\\\"Status\\\":true,\\\"ID\\\":24501}\"";
When I use the Parse method like below I run into an error stated below:
JObject o = JObject.Parse(json);
Error reading JObject from JsonReader. Current JsonReader item is not an object: String
How do I get rid of this error or is there any other method to parse my json string and fetch the values?
Remove first and last quotes:
string json = "{\"Status\":true,\"ID\":24501}";
See the Json format here.
It seems like your object is double encoded. Try:
string json = "{\"Status\":true,\"ID\":24501}";
You need something like this
json = json.Replace(#"\", string.Empty).Trim(new char[]{'\"'})
in here format should be something like this:
string jsonNew = #"{'Status': True,'ID': 24501 }";
As SolarBear says in his comment, the problem is double-escaping.
To get the proper format, like this:
string json = "{\"Status\":true,\"ID\":24501}";
Do something like this:
json = json.Replace("\\\\", "\\");
Had similar issue today. My solution to this is contained in this extension method (using c#):
public static class StringExtensions
{
public static string RemoveDoubleEncoding(this string text)
{
if(string.IsNullOrEmpty(text))
return string.Empty;
var result = text.TrimStart('\"').TrimEnd('\"');
result = result.Replace(#"\", string.Empty);
return result;
}
}
Related
I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:
{"json":"{\"count\":\"123\"}"}
The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".
The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.
The testing code I used is like this.
[TestMethod()]
public void JsonParseTest()
{
var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
var jObject = JObject.Parse(json);
Console.WriteLine($"json : {json}");
Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}
We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)
EDIT 1
The version of NewtonSoft is 12.0.3 released in 2019.11.09.
The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.
If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):
{"json":"{\\\"count\\\":\\\"123\\\"}"}
with leads to the C# code:
var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";
Is there a way to convert string to json in Ballerina ?
I found this PR - Add jsons:parse() method to get a JSON from a string where it says adding support to parse string to json, but couldn't find any example.
I tried the following:
string person = {"name":"John", "address":{"number":89, "street":"main street", "town": "Colombo"}};
json personJson = sons:parse(person);
But it gave me an error:
undefined package 'jsons'
undefined function 'parse'
The correct way to convert a string to json in ballerina is to use the readJson function from StringReader. What you have tried was an old approach which is no longer supported.
Following example shows how this could be done using the StringReader.
import ballerina/io;
public function main(string... args) {
string str = "{\"name\":\"John\", \"address\":{\"number\":89, \"street\":\"main street\", \"town\":\"Colombo\"}}";
io:StringReader sr = new(str, encoding = "UTF-8");
json j = check sr.readJson();
io:println(j);
}
More info about StringReader can be found from the docs at - https://ballerina.io/learn/api-docs/ballerina/io.html#StringReader
From Ballerina swan lake onward, you can use the fromJsonString() method to convert a string to json:
string jsonStr = "{\"key\": \"value\"}";
json|error converted = jsonStr.fromJsonString();
if (converted is error) {
io:println("Error in parsing json");
} else {
io:println(converted);
}
My controller is as follows...
public IHttpActionResult GetData()
{
IEnumerable<dynamic> result = api.getData();
string json = JsonConvert.SerializeObject(result);
return Ok(json);
}
returns raw text from fiddler
{"#odata.context":"https://localhost:44305/api/$metadata#Edm.String","value":"[\r\n {\r\n \"UserName\": \"test#gmail.com\"\r\n }\r\n]"
You notice the JSON object for value has double quotes around it and the special characters \r\n. How do I get it to return pure JSON format???
I am not getting more details from your code but have you tried this way.
Is there any specific reason to use a serialized object?
[System.Web.Http.HttpGet]
public IEnumerable<XYZ> GetData()
{
return api.GetData();
}
Hope this helps!!!
It's by design since you are returning a json string..
Do this in js: JSON.parse(response.data)
I'm trying to use json.net.
I'd like to get a string (in json format) and convert it to general json object, without predefined schema.
somelting like
var jsonString = #"{\""id\"": 1,\""name\"": \""A green door\""}";
var jsonMessage = JsonConvert.DeserializeObject<JObject>(jsonString);
var myValue = jsonMessage["name"]
Is that something doable? didn't make it work
Your string is malformed, try this string instead:
var jsonString = "{\"id\": 1,\"name\": \"A green door\"}";
You could also shorten this a little bit:
string name = JObject.Parse(jsonString)["name"].ToObject<string>();
I am trying to receive a JSON string in salesforce by converting a blob in the body of an Http request. However, when I convert the blob to a string there are \ characters that get inserted into the request which prevents me from parsing.
I then tried to take the string and remove all \ characters... that didn't work either.
RestRequest req = RestContext.request;
Blob jsonBlob = req.requestBody;
String jsonString = jsonBlob.toString();
return jsonString;
The original string (the one that is received as a blob) looks like this:
{"putTimeCard":{"timecard":{"timeCardID": "","employeeID": ""}}
And after converting to a salesforce string and assigned to the jsonString is altered to:
{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}
Has anyone found a solution for this?
Thanks
The JSON Deserializer can parse the string with the escape characters. You can either deserialize into an object like so:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Timecard t = (Timecard) JSON.deserialize(jsonString, Type.forName('Timecard'));
or if you just want a map of objects you can do the following:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonString);