How to safely convert a string containing escaped JSON to valid JSON?

I am communicating with a third-party API that returns JSON responses as follows:

"{\"SomeResponse\":{\"FIrstAttribute\":8,\"SecondAttribute\":\"On\",\"ThirdAttribute\":{\"Id\":2,\"FirstName\":\"Okkie\",\"Name\":\"Bokkie\",\"Street\":\"\",\"StreetNumber\":null,\"PostCode\":\"\",\"City\":\"\",\"Country\":\"}}}" 

This is kind of JSON ... but as a string. Pay attention to the first and final double quotes and, of course, to all slashes.

I am currently resolving this by String.Replacing a backslash and a first and final quote. After that I can take it apart.

 mystring.Replace("\\", ""); 

However, what if one of the attributes has a backslash as a value? For example:

 \"SecondAttribute\":\"My Super Back Slash: \\ . That was it.\" 

In this case, I accidentally delete the backslash, which should be there in the value.

Does anyone have a bright idea on how to parse this JSON string correctly?

+9
json string c #
source share
3 answers

This is basically JSON encoded as a JSON string - after a little study of the end of the string, as in the comments. It is difficult to do this in Json.NET using JToken.Parse to efficiently execute unescape, and then parse the result:

 using System; using System.IO; using Newtonsoft.Json.Linq; class Program { static void Main(string[] args) { string text = File.ReadAllText("test.json"); JToken token = JToken.Parse(text); JObject json = JObject.Parse((string) token); Console.WriteLine(json); } } 

Output:

 { "SomeResponse": { "FIrstAttribute": 8, "SecondAttribute": "On", "ThirdAttribute": { "Id": 2, "FirstName": "Okkie", "Name": "Bokkie", "Street": "", "StreetNumber": null, "PostCode": "", "City": "", "Country": "" } } } 

This should be good even with backslash data, as I would expect the backslash to be encoded again - but it would be worth checking this twice.

+14
source share

Using Newtonsoft.Json, here is an example:

 String json="{\"SomeResponse\":{\"FIrstAttribute\":8,\"SecondAttribute\":\"On\",\"ThirdAttribute\":{\"Id\":2,\"FirstName\":\"Okkie\",\"Name\":\"Bokkie\",\"Street\":\"\",\"StreetNumber\":null,\"PostCode\":\"\",\"City\":\"\",\"Country\":\"}}}"; dynamic result = JsonConvert.DeserializeObject(json); 

+3
source share

Wow ... this is not JSON at all. This is a weird JSON-like fake, but pretty nasty. I think you are doing the right thing.

The only thing I can do is perform the replace operation on character pairs, and not just one escape char:

myString.Replace(@"\""", @"""); // replace \" with "

This will allow you to safely save nested "\" chararcters, so the filtered JSON looks like this:

field_blah: "root\branch\sub-branch"

I highly recommend doing a detailed review of the "JSON" text and making sure that this is the only pairing sequence you need to worry about. If you have other pairs, treat them the same way as described above.

+1
source share

All Articles