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

后端 未结 4 664
广开言路
广开言路 2020-12-25 13:55

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

\"{\\\"SomeResponse\\\":{\\\"FIrstAttribute\\\":8,\\\"SecondAttribute\\\":\         


        
相关标签:
4条回答
  • 2020-12-25 14:43

    Ugh... that's not JSON at all. It's a weird JSON-like imitation, but a pretty nasty one. I think you're doing the right thing.

    The only thing that I might do is do the replace operation on pairs of characters rather than just the single escape char:

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

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

    field_blah: "root\branch\sub-branch"

    I strongly advise undertaking a detailed review of the "JSON" text and ensuring that this is the only paired sequence you need to worry about. If you have other pairings, handle them in the same manner as outlined above.

    0 讨论(0)
  • 2020-12-25 14:47

    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.

    0 讨论(0)
  • 2020-12-25 14:49

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

    0 讨论(0)
  • 2020-12-25 15:00
    var JsonRequest = JToken.Parse(rawjson).ToString(Newtonsoft.Json.Formatting.None);
    
    0 讨论(0)
提交回复
热议问题