【问题标题】:Deserialize a JSON Schema with JSON.Net使用 JSON.Net 反序列化 JSON Schema
【发布时间】:2014-02-19 21:33:58
【问题描述】:

我想使用 JSON.Net 反序列化此架构。

{ 
  "color" : { 
    "type" : "String", 
    "description" : "What color do you want your taco", 
    "required" : false, 
    "default" : "Green", 
    "options" : [ "Green", "Blue", "Red"]
  },
  "include_beans" : { 
    "type"  : "Boolean", 
    "description" : "Do you want beans on your taco", 
    "required" : false, 
    "default" : false 
  }, 
  "pounds"  : { 
    "type" : "Double", 
    "description" : "How  many pounds of meat do you want?", 
    "required"  : false, 
    "default" : 0.1 
  },  
  "count" : { 
    "type"  : "Integer", 
    "description" : "How  many tacos would you like?", 
    "required"  : false, 
    "default" : 0.0 
  }
}

请注意,每个属性都具有相同的结构。我想要结束的是Dictionary<string, TacoProperty>,其中TacoProperty 定义为:

public class TacoProperty
{
    public string type { get; set; }
    public string description { get; set; }
    public bool required { get; set; }
    [JsonProperty(PropertyName = "default")]
    public string defaultValue { get; set; }
    public List<string> options { get; set; }
}

字典中的键应该是“color”、“include_beans”等,所有TacoPropertys应该是值。

【问题讨论】:

  • 那么你尝试了什么(知道目标类型),什么没有奏效? Json.NET 完全能够直接反序列化为Dictionary&lt;string,X&gt;
  • 可能是因为没有提出任何问题,只有一个任务和所有信息可用于尝试某些东西(这可能会起作用或导致错误/问题)。
  • 例如包括这里的自我发布的答案,因为“这是我所拥有的,它有效,但它似乎不是很优雅”将构成 some 问题。确定一个特定的问题非常重要。
  • 为了将来参考,我相信像这样的问题(你写了一些代码,它可以工作,但可能不是最优雅的代码)更适合codereview.stackexchange.com
  • 很高兴知道。谢谢你的提示。我只使用了 Q 和 A 格式,因为我不知道是否有更好的方法,但无论如何它可能对其他人有用。

标签: c# json json.net deserialization jsonschema


【解决方案1】:

Json.NET 可以直接反序列化数据:

var tacoProperties =
       JsonConvert.DeserializeObject<IDictionary<string, TacoProperty>>(json);

【讨论】:

  • 谢谢。这比我的方式优雅得多。我不知道它会自动使用 Path 作为键。
  • 这就是 SO 的意义所在,但我因为试图学习一种更好的方法来做某事而被否决。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多