【问题标题】:Deserializing Json Schema to Json String or Object将 Json Schema 反序列化为 Json 字符串或对象
【发布时间】:2016-03-06 12:05:50
【问题描述】:

我有一个 json 架构,我需要将其转换为 C# 对象或至少转换为 json 字符串。

有没有办法通过代码或使用一些工具来做到这一点?

对于我目前使用的 Json Json.net

这是我的架构之一:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "UserGroupWsDTO",
  "type": "object",
  "properties":
  {
    "members":
    {
      "type": "array",
      "items":
      {
        "type": "object",
        "properties":
        {
          "uid":
          {
            "type": "string"
          }
        }
      }
    },
    "uid":
    {
      "type": "string"
    },
    "name":
    {
      "type": "string"
    }
  }
}

我需要这个来创建一个反序列化 json 的对象

编辑 我的 Json 架构版本是 4 并且 JSON Schema to POCO 不支持它

【问题讨论】:

标签: c# json json.net


【解决方案1】:

查看支持 v3 JSON 的 JSON Schema to POCO

【讨论】:

    【解决方案2】:

    如果您只是“浏览”key-values,那么您不需要任何额外的库...

    只是做:

    var obj = (JObject)JsonConvert.DeserializeObject(json);
    
    var dict = obj.First.First.Children().Cast<JProperty>()
                .ToDictionary(p => p.Name, p =>p.Value);
    
    var dt =  (string)dict["title"];
    

    但是,如果您需要字符串的对象,则定义一个类并将字符串反序列化为该类...遵循以下示例:

    首先定义类:

    public class Uid
    {
        public string type { get; set; }
    }
    
    public class Properties2
    {
        public Uid uid { get; set; }
    }
    
    public class Items
    {
        public string type { get; set; }
        public Properties2 properties { get; set; }
    }
    
    public class Members
    {
        public string type { get; set; }
        public Items items { get; set; }
    }
    
    public class Uid2
    {
        public string type { get; set; }
    }
    
    public class Name
    {
        public string type { get; set; }
    }
    
    public class Properties
    {
        public Members members { get; set; }
        public Uid2 uid { get; set; }
        public Name name { get; set; }
    }
    
    public class RootObject
    {
        public string __invalid_name__$schema { get; set; }
        public string title { get; set; }
        public string type { get; set; }
        public Properties properties { get; set; }
    }
    

    这是实现:

     string json = @"{...use your json string here   }";
    
        RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
    
        Console.WriteLine(root.title);
        // UserGroupWsDTO
    

    【讨论】:

    • 我需要一个对象来反序列化 json
    • 我的问题是如何获取 json,否则创建“Account”对象我需要读取 Json 模式
    • @frenk91,新变化,请再次查看更新后的答案。
    • 在任意模式中,您可能需要解析类型引用等
    猜你喜欢
    • 2014-01-04
    • 2020-02-03
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多