C# – 无法反序列化当前的JSON数组时出错

huangapple go评论90阅读模式
英文:

C# - Error where cannot deserialize the current JSON array

问题

我想显示州和城市的列表。

以下是我做的州和城市列表:

```json
[
  { "State": "California", 
    "City": 
      ["Los Angeles", 
       "San Diego", 
       "San Francisco" 
      ]
   }, 
   { "State": "Texas", 
     "City": 
       ["Houston", 
        "San Antonio", 
        "Dallas"
       ]
    }
]

这是我的代码:

List<string> stateCities = new List<string>();
var dictionary = stateCities.Select(x => JsonConvert.DeserializeObject<Dictionary<string, object>>(x))
     .ToDictionary(x => x["State"].ToString(), x => ((JArray)x["City"]).ToObject<List<string>>());

lookUpEditState.Properties.DataSource = dictionary;
lookUpEditState.Properties.ValueMember = "State";
lookUpEditCity.Properties.DataSource = dictionary;
lookUpEditCity.Properties.ValueMember = "City";
lookUpEditCity.CascadingOwner = lookUpEditState;

我得到了这个错误:

设置失败:无法将当前的 JSON 数组(例如 [1,2,3])反序列化为类型 'System.Collections.Generic.Dictionary`2[System.String,System.Object]',因为该类型需要一个 JSON 对象(例如 {"name":"value"})才能正确反序列化。
要解决此错误,要么将 JSON 更改为 JSON 对象(例如 {"name":"value"}),要么将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),如可从 JSON 数组反序列化的 List
也可以向类型添加 JsonArrayAttribute,强制它从 JSON 数组反序列化。路径 '', 第1行,第1个位置。

有什么办法可以解决这个问题吗?谢谢


<details>
<summary>英文:</summary>

I want to display the list of state and city.

The following is the list for state and city that I&#39;ve done:

```json
[
  { &quot;State&quot;: &quot;California&quot;, 
    &quot;City&quot;: 
      [&quot;Los Angeles&quot;, 
       &quot;San Diego&quot;, 
       &quot;San Francisco&quot; 
      ]
   }, 
   { &quot;State&quot;: &quot;Texas&quot;, 
     &quot;City&quot;: 
       [&quot;Houston&quot;, 
        &quot;San Antonio&quot;, 
        &quot;Dallas&quot;
       ]
    }
]

Here is my code

List&lt;string&gt; stateCities = new List&lt;string&gt;();
                var dictionary = stateCities.Select(x =&gt; JsonConvert.DeserializeObject&lt;Dictionary&lt;string, object&gt;&gt;(x))
                     .ToDictionary(x =&gt; x[&quot;State&quot;].ToString(), x =&gt; ((JArray)x[&quot;City&quot;]).ToObject&lt;List&lt;string&gt;&gt;());

                    lookUpEditState.Properties.DataSource = dictionary;
                    lookUpEditState.Properties.ValueMember = &quot;State&quot;;
                    lookUpEditCity.Properties.DataSource = dictionary;
                    lookUpEditCity.Properties.ValueMember = &quot;City&quot;;
                    lookUpEditCity.CascadingOwner = lookUpEditState;
                }

i got this error:

> Fail to setup: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]' 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 '', line 1, position 1.

Any idea how can i fix this? Thank you

答案1

得分: 2

你需要使用与其表示匹配的类来反序列化JSON。在这种情况下,你有一个具有State和City属性的对象数组,所以你可以这样使用:

var template = new [] { new { State = "", City = new string[] {} }};
var array = JsonConvert.DeserializeAnonymousType(jsonText, template);

如果你真的想要,然后你可以将其转换为字典:

var dictionary = array.ToDictionary(x => x.State, y => y.City);

...这将给你一个 Dictionary<string, string[]>

英文:

You need to deserialize JSON using a class that matches its representation. In this case you have an array of objects that have a State and City property, so you could use this:

var template = new [] { new { State = &quot;&quot;, City = new string[] {} }};
var array = JsonConvert.DeserializeAnonymousType(jsonText, template);

You could then convert it to a dictionary if you really want:

var dictionary = array.ToDictionary( x =&gt; x.State, y =&gt; y.City );

...which will give you a Dictionary&lt;string,string[]&gt;.

答案2

得分: 1

这对我有效

  Dictionary&lt;string, List&lt;string&gt;&gt; dictionary = JArray.Parse(json)
						.ToDictionary(ja =&gt; (string)ja[&quot;State&quot;],ja =&gt; ja[&quot;City&quot;]
						.Select(i =&gt; (string)i).ToList());
英文:

This works for me

  Dictionary&lt;string, List&lt;string&gt;&gt; dictionary = JArray.Parse(json)
						.ToDictionary(ja =&gt; (string)ja[&quot;State&quot;],ja =&gt; ja[&quot;City&quot;]
						.Select(i =&gt; (string)i).ToList());

</details>



huangapple
  • 本文由 发表于 2023年6月16日 10:01:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定