如何安全地将包含转义JSON的字符串转换为有效JSON? [英] How to safely convert a string containing escaped JSON to valid JSON?

查看:1029
本文介绍了如何安全地将包含转义JSON的字符串转换为有效JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与返回JSON响应的第三方API通信,如下所示:

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

这是一种JSON ...但作为字符串。请注意首尾双引号和

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

当前,我通过String解决此问题,替换反斜杠以及第一个和最后一个引号,然后我就可以解析它了。

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.

有人对如何正确解析此JSON字符串有聪明的主意吗?

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

推荐答案

这基本上是JSON编码的 作为JSON字符串-根据注释,在对字符串的末尾进行了非常细微的修改之后,在Json中处理起来并不难。 NET,先使用 JToken.Parse 有效地转义,然后解析结果:

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

输出:

{
  "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.

这篇关于如何安全地将包含转义JSON的字符串转换为有效JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆