14

当我尝试使用 Newtonsoft.Json 解析我的 JSON 时出现以下错误

Response result = JsonConvert.DeserializeObject<Response>(unfilteredJSONData);

无法将属性字符串添加到 Newtonsoft.Json.Linq.JObject。对象上已存在同名属性。

我无法控制 JSON 提要,他们只是添加了flags1flags2. 重复的字符串似乎导致了错误,但我对如何解决它没有任何好主意。在添加新字段之前,此代码运行良好。

更新:


第一个错误是由使用过时的 JSON.net 版本引起的。我正在使用的 CMS 系统有一个内置版本,它是 3.5。当我使用 4.5 时,我收到一个新错误:

无法将 Newtonsoft.Json.Linq.JValue 添加到 Newtonsoft.Json.Linq.JObject。

事实证明,我下面的 JSON 格式与我正在处理的格式不完全相同。请注意更新。错误似乎是在这里引起的:

"flags1": {
    "string": "text",
    "string": "text"
},

JSON是:

{
    "result":
    {
        "lookups":
        [
            {
                "groups":
                [
                    {
                        "item0": "text",
                        "item1": "text",
                        "item2": 0,
                        "item3": 0,
                        "item4": 11.5,
                        "item5": true
                    },
                    {
                        "item6": "text",
                        "oddName": "text"
                    },
                    {
                        "item7": {
                            "subitem0": "text",
                            "subitem1": 0,
                            "subitem2": true
                        },
                        "item8": {
                            "subitem0": "string",
                            "subitem1": 0,
                            "subitem2": true
                        }
                    },
                    {
                        "url": "http://google.com",
                        "otherurl": "http://yahoo.com",
                        "alturllist": [],
                        "altotherurl": []
                    },
                    {},
                    {
                        "flags1": {
                            "string": "text"
                        },
                        "flags2": {
                            "string": "text"
                        }
                    }
                ]
            },
            {
                "groups":
                [
                    {
                        "item0": "text",
                        "item1": "text",
                        "item2": 0,
                        "item3": 0,
                        "item4": 11.5,
                        "item5": true
                    },
                    {
                        "item6": "text",
                        "oddName": "text"
                    },
                    {
                        "item7": {
                            "subitem0": "text",
                            "subitem1": 0,
                            "subitem2": true
                        },
                        "item8": {
                            "subitem0": "string",
                            "subitem1": 0,
                            "subitem2": true
                        }
                    },
                    {
                        "url": "http://google.com",
                        "otherurl": "http://yahoo.com",
                        "alturllist": [],
                        "altotherurl": []
                    },
                    {},
                    {
                        "flags1": {
                            "string": "text",
                            "string": "text"
                        },
                        "flags2": {}
                    }
                ]
            }
        ]
    }
}

C# 类是:

// response
[DataContract]
public class Response
{
    [DataMember(Name = "result")]
    public Result result { get; set; }
}
[DataContract]
public class Result
{
    [DataMember(Name = "lookups")]
    public List<Item> lookups { get; set; }
}
[DataContract]
public class Item
{
    [DataMember(Name = "groups")]
    public List<Dictionary<string, object>> groups { get; set; }
}

为了清楚起见,我简化了 JSON 和代码示例。

我包含了代码 aspx 以简化复制。

测试.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <code>
    <%=response %>
    </code></div>
    </form>
</body>
</html>

测试.aspx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using NLog;

public partial class Test : System.Web.UI.Page
{
    public string response = string.Empty;
    public static string cacheDirPath = HttpRuntime.AppDomainAppPath + "cache\\";
    private static Logger log = LogManager.GetLogger("productFeed");

    protected void Page_Load(object sender, EventArgs e)
    {

        response = readDataFromFile(cacheDirPath + "test2.json");
        Response masheryResult = JsonConvert.DeserializeObject<Response>(response);
    }
    private string readDataFromFile(string filePath)
    {
        string JSONData = string.Empty;
        try
        {
            StreamReader myFile = new StreamReader(filePath);

            JSONData = myFile.ReadToEnd();

            myFile.Close();
        }
        catch (Exception e)
        {
            log.Warn(e.Message);
        }

        return JSONData;
    }
}

// response
[DataContract]
public class Response
{
    [DataMember(Name = "result")]
    public Result result { get; set; }
}
[DataContract]
public class Result
{
    [DataMember(Name = "lookups")]
    public List<Item> lookups { get; set; }
}
[DataContract]
public class Item
{
    [DataMember(Name = "groups")]
    public List<Dictionary<string, object>> groups { get; set; }
}
4

2 回答 2

19

“flags1”对象中的两个属性都被命名为“string”,你不能定义一个属性两次。

编辑:看来,至少在最新的 nuget 版本中,JObject.Parse 跳过了错误并正确解析了数据!我希望你能为你做这件事。

这是一个如何做到这一点的示例:

Response result = JObject.Parse(unfilteredJSONData).ToObject<Response>();
于 2013-02-26T15:13:44.607 回答
3

除了Connor Hilarides回答之外,它还可以用于包括数组:

JToken resultToken = JToken.Parse(unfilteredJSONData);
于 2015-09-08T16:39:42.187 回答