Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

string

c#

.net

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\":\"}}}"

It is kind of JSON... but as a String. Note the first and ending double quotes and of course all the escape slashes.

Currently, I solve this by String.Replacing the backslashes and the first and end quote. After that, I am able to parse it.

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

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

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

In that case, I would accidentally remove the backslash that should be there in the value.

Does anyone have a bright idea on how to parse this JSON String properly?

like image 249
Gonzalioz Avatar asked Oct 16 '14 12:10

Gonzalioz


2 Answers

This is basically JSON encoded as a JSON string - after doctoring the end of your string very slightly, as per comments. It's not too hard to handle that in Json.NET, using JToken.Parse to effectively unescape first, then parsing 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": ""
    }
  }
}

That should be fine even with data containing backslashes, as I'd expect the backslashes to be encoded once again - but it would be worth double-checking that.

like image 175
Jon Skeet Avatar answered Oct 20 '22 16:10

Jon Skeet


By 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);

like image 35
Juan Castillo Avatar answered Oct 20 '22 14:10

Juan Castillo