[英]Deserializing Json Schema to Json String or Object
I have a json schema and I need to convert it to a C# object or at least into json string. 我有一个json模式,我需要将其转换为C#对象或至少转换为json字符串。
is there any way to do it by code or by using some tool? 有什么办法可以通过代码或使用某种工具来做到这一点?
for the Json I'm currently using Json.net
. 我目前正在使用Json.net
的Json。
this is one of my schema: 这是我的模式之一:
{
"$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"
}
}
}
I need this to create an Object for deserialize the json 我需要这个来创建一个对象以反序列化json
EDIT My Json schema version is 4 and JSON Schema to POCO doesn't support it 编辑我的Json模式版本为4,并且POCO的JSON模式不支持它
查看支持v3 JSON的POCO的JSON模式 。
If you are just "browsing" key-values
, then you don't need any extra libs... 如果只是“浏览” key-values
,则不需要任何额外的库...
just do: 做就是了:
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"];
but if instead you need an object of the string, then define a class and deserialize the string to that class... follow this example: 但是如果您需要一个字符串对象,则定义一个类并将字符串反序列化为该类...请遵循以下示例:
1st define the classes: 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; }
}
and this is the implementation: 这是实现:
string json = @"{...use your json string here }";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(root.title);
// UserGroupWsDTO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.