【问题标题】:Cannot identify data structure from JSON to deserialize into object无法从 JSON 中识别数据结构以反序列化为对象
【发布时间】:2019-03-06 09:58:36
【问题描述】:

将 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.

也尝试过使用地图和字符串(多维)数组,但遇到了同样的异常......

【问题讨论】:

  • 你尝试过创建一个包含太阳、行星、地球、星系的类吗?
  • 我认为你的意思是Dictionary&lt;string, string&gt; Newtonsoft 非常擅长将 JSON 对象转换为该模型。
  • @BugFinder 那些名字可以是任何东西,我无法命名。
  • @er-sho 我不知道,我不是该模型的创建者,只需要使用它。在发送到目标服务器之前,我需要对其进行反序列化,然后进行序列化(以相同的格式)。
  • @VladacusB 从您的帖子中不清楚这些名称正在改变

标签: c# json serialization json.net


【解决方案1】:

对我来说,它看起来像 Dictionary

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

【讨论】:

  • 不知怎的我错过了,它是字典,谢谢!
【解决方案2】:

使用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;

输出:

【讨论】:

  • 那些变量名可以是任何东西。它们不能被硬编码。
  • @VladacusB,答案已更新,但让我知道您想在将数据输入字典后如何处理它?
【解决方案3】:

在我看来它是一个简单的类。

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);

【讨论】:

  • 你错了,这些变量名不是硬编码的。它们可以是任何东西。
  • 我很欣赏否决票,但你没有提到这一点。如果是这种情况,您应该使用 Dictionary,就像其他人提到的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2022-07-05
  • 2014-08-04
  • 1970-01-01
相关资源
最近更新 更多