使用Newtonsoft.Json解析Json字符串时出错

时间:2011-08-15 21:34:30

标签: json parsing json.net

我的JSON字符串如下所示。请注意,它有转义字符。

string json = "\"{\\\"Status\\\":true,\\\"ID\\\":24501}\"";

当我使用如下的Parse方法时,我遇到了下面所述的错误:

JObject o = JObject.Parse(json);

从JsonReader读取JObject时出错。当前JsonReader项不是对象:String

如何摆脱此错误或是否有其他方法来解析我的json字符串并获取值?

6 个答案:

答案 0 :(得分:4)

删除第一个和最后一个引号:

string json = "{\"Status\":true,\"ID\":24501}";

请参阅Json格式here

答案 1 :(得分:2)

好像你的对象是双重编码的。尝试:

string json = "{\"Status\":true,\"ID\":24501}";

答案 2 :(得分:1)

你需要这样的东西

json = json.Replace(@"\", string.Empty).Trim(new char[]{'\"'})

答案 3 :(得分:0)

这里的格式应该是这样的:

string jsonNew = @"{'Status': True,'ID': 24501 }";

答案 4 :(得分:0)

正如SolarBear在评论中所说,问题是双重逃避。

要获得正确的格式,请执行以下操作:

string json = "{\"Status\":true,\"ID\":24501}";

做这样的事情:

json = json.Replace("\\\\", "\\");

答案 5 :(得分:0)

今天有类似的问题。我的解决方案包含在此扩展方法中(使用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;
    }
}