使用Newtonsoft,C#反序列化JSON时出错

时间:2018-06-27 16:29:13

标签: javascript c# asp.net json

我收到以下错误:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[ReportingDataSchema.CurrentBusinessUnits]]' 
because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly. 
To fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. 
JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'selectedBusinessUnits', line 1, position 26."} System.Exception {Newtonsoft.Json.JsonSerializationException}

我的JSON:

{
  "selectedBusinessUnits": [{
    "guidNode": "some value",
    "businessUnit": "some value",
    "fileName": "some value"
  }, {
    ...
  }]
}

我正在尝试首先将此响应转换为以下内容:

public class EnAFileGenerator
{
    private Dictionary<string, List<CurrentBusinessUnits>> selectedBusinessUnits;

    public Dictionary<string, List<CurrentBusinessUnits>> SelectedBusinessUnits 
    {
        get { return selectedBusinessUnits; }
        set { selectedBusinessUnits = value; }
    }
}

这样,最终我可以使用以下命令访问JSON中的数组:

public class CurrentBusinessUnits
{
    private string guidNode;
    private string businessUnit;
    private string fileName;

    public string GuidNode { get; set; }
    public string BusinessUnit { get; set; }        
    public string FileName { get; set; }       
}

产生错误的代码:

// JSON Data is the parameter from the client, containing the above JSON object
EnAFileGenerator resultArray = JsonConvert.DeserializeObject<EnAFileGenerator>(JSONData);

从我的阅读中看来,我的错误似乎是由于将数组(属性selectedBusinessUnits的值)解析为所需的C#集合而导致的。

实施@DavidG的建议后,我仍然收到以下消息:

Error converting value \"{\"guidNode\":\"some value\",\"businessUnit\":\"some value\",\"fileName\":\"some value.xlsx\"}\" 
to type 'ReportingDataSchema.CurrentBusinessUnits'. Path 'selectedBusinessUnits[0]', line 1, position 159."}    
System.Exception {Newtonsoft.Json.JsonSerializationException}

Prany的解决方案几乎使我到了那里。我能够修改该代码以利用我已经拥有的对象:

var files = JObject.Parse(JSONData);
var recList = files.SelectToken("$..selectedBusinessUnits").ToList();

foreach (string item in recList)
{
    JObject businessUnit = JObject.Parse(item);

    CurrentBusinessUnits currentBusinessUnit = businessUnit.ToObject<CurrentBusinessUnits>();
}

2 个答案:

答案 0 :(得分:4)

问题是您正在尝试反序列化为错误的类型。您已经指定了Dictionary<string, List<CurrentBusinessUnits>>,但实际上您只需要一个List<CurrentBusinessUnits>

public class EnAFileGenerator
{
    public List<CurrentBusinessUnits> SelectedBusinessUnits { get; set; }
}

答案 1 :(得分:1)

由于使用的是Newtonsoft,因此可以使用Jobject。用于基于选定的BusinessUnits获取值。在下面使用

var files = JObject.Parse(YourJson);
var recList = files.SelectToken("$..selectedBusinessUnits").ToList();
foreach (JObject item in recList)
{
   foreach (JProperty prop in item.Children())
      {
         string key = prop.Name.ToString();
         string value = prop.Value.ToString();
      }
}