无法从JSON识别数据结构以反序列化为对象

时间:2019-03-06 09:58:36

标签: c# json serialization json.net

将json字符串反序列化为对象时出现问题。 主要问题是我无法识别此字符串代表的对象类型:

string jsonDataText = @"{""sun"":""heat"", ""planet"":""rock"", ""earth"":""water"", ""galaxy"":""spiral""}";

它看起来像KeyValuePair对象的列表,但是当我尝试使用Newtonsoft.Json反序列化时:

var clone = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(jsonDataText);

我有一个例外:

 Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.String,System.String]]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

也尝试过使用Maps和字符串(多维)数组,但有相同的例外...

3 个答案:

答案 0 :(得分:2)

对我来说,它就像是Dictionary

 JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonDataText);

答案 1 :(得分:0)

使用JObject可以轻松地从JSON中读取任何键/值对。

因此,您不再需要在json中识别键/值对的类型。

string jsonDataText = @"{""sun"":""heat"", ""planet"":""rock"", ""earth"":""water"", ""galaxy"":""spiral""}";

//Parse your json to dictionary
Dictionary<string, string> dict = JObject.Parse(jsonDataText).ToObject<Dictionary<string, string>>();  

您需要将此名称空间添加到您的程序=> using Newtonsoft.Json.Linq;

输出:

enter image description here

答案 2 :(得分:-1)

在我看来,这是一个简单的课程。

public class MyClass
{
    [JsonProperty("sun")]
    public string Sun { get; set; }

    [JsonProperty("planet")]
    public string Planet { get; set; }

    [JsonProperty("earth")]
    public string Earth { get; set; }

    [JsonProperty("galaxy")]
    public string Galaxy { get; set; }
}

反序列化:

var clone = JsonConvert.DeserializeObject<MyClass>(jsonDataText);