将Json Schema反序列化为Json字符串或对象
问题描述:
我有一个json模式,我需要将它转换为C#对象或至少将其转换为json字符串。将Json Schema反序列化为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来POCO没有按” t支持它
答
如果你只是“浏览”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"];
,但如果相反,你需要的字符串对象,然后定义一个类和反序列化串的那类......按照这个例子:
1定义类:
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
转到http://json2csharp.com/并粘贴你的json - 所有的类都将为你创建。 – Ric
可能重复[从JSON模式生成C#类](http://stackoverflow.com/questions/6358745/generate-c-sharp-classes-from-json-schema) – eoinmullan
我不能使用json2csharp,因为我有一个Json架构。 – frenk91