JObject.Parse在有效的Json上抛出错误

时间:2016-06-20 21:51:20

标签: json.net

'Newtonsoft.Json.JsonReaderException: Additional text encountered after finished reading JSON content: {. Path '', ...'上搜索至少发现3个SO问题,所有这些问题都被追溯到无效的Json。

我尝试了3种不同的验证器:

[{"Imported": "This registration imported on: 06/20/2016"},{"ContactInfoUpdated": " Street Address2: Suite 222   to  Shipping Address2:   "}]

并且所有三个都报告为有效。然而,运行时错误抛出相同的'遇到的其他文本......'

if (!string.IsNullOrWhiteSpace(UserComments))
{
    JToken addresses;
    addresses = JObject.Parse(UserComments).GetValue("CarbonCopy"); //errors here
    if (!ReferenceEquals(null, addresses))
    {
      //stuff
    }
}

要确定json关闭后没有非预期的字符,这里是sql:

UPDATE dbo.[Order] SET UserComments = '[{"Imported": "This registration imported on: 06/20/2016"},{"ContactInfoUpdated": " Street Address2: Suite 222   to  Shipping Address2:   "}]' WHERE idOrder =121050 

1 个答案:

答案 0 :(得分:0)

感谢Brian的提示,我发现这篇文章非常有用:

Get Value from JSON using JArray

我的json有点不寻常,因为它是一组不同的对象。我的'UserComments'字段包含名称可以是' ProfileWasEdited '的对,而不是名称保持不变的一系列名称/值对, ' CCRequested ','反馈',依此类推。

为了适应这种类型的结构,我需要针对名称属性进行测试:

var fields = JToken.Parse(UserComments);
var isCC = "";
foreach (JObject content in fields.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        if (prop.Name == "CarbonCopy")
        isCC = prop.Value.ToString(); 
    }
}

Resharper通知我,我可以将上述内容简化为:

foreach (JProperty prop in fields.Children<JObject>().SelectMany(content => content.Properties().Where(prop => prop.Name == "CarbonCopy")))
{
    isCC = prop.Value.ToString();
}