我正在生成以下JSON格式,有人可以告诉我如何将其转换回我的课程。
["Node1",{"DictionaryNode1_1":"NodeValue1","DictionaryNode1_2":"NodeValue2","DictionaryNode1_3":"NodeValue3"},["Node11",{"DictionaryNode11_1":"NodeValue1","DictionaryNode11_2":"NodeValue2","DictionaryNode11_3":"NodeValue3"},"Node12",null,["Node121",null,["Node1211",{"DictionaryNode1211_1":"NodeValue1","DictionaryNode1211_2":"NodeValue2","DictionaryNode1211_3":"NodeValue3"}]]],"Node2",null,["Node21","Node22"]]
如何使用以下转换器方法实现此目的。
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
}
以下是转换类。
[JsonConverter(typeof(TreeNodeConverter))]
public class SubTreeNode : TreeNode
{
private Dictionary<string, string> _dicAttr;
public Dictionary<string,string> dicAttr
{
get
{
return _dicAttr;
}
set
{
_dicAttr = value;
}
}
}
答案 0 :(得分:2)
您可以使用JSON.NET完成几乎所有基于JSON序列化字符串的操作。因此,对于您的示例,如果我理解正确,您只需要将字符串反序列化为Dictionary<string,string>
(或Dictionary<string,Dictionary<string, string>>
...)类型,因此以下是需要考虑的一些主题:
- Deserialize to Object
- Or you can deserialize to dynamic
and do whatever you like after it (for C# 4 and one of the latest Json.NET versions)
- Querying JSON with dynamic
以下是来自Json.net的示例,反序列化为dynamic:
string json = @"[
{
'Title': 'Json.NET is awesome!',
'Author': {
'Name': 'James Newton-King',
'Twitter': '@JamesNK',
'Picture': '/jamesnk.png'
},
'Date': '2013-01-23T19:30:00',
'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
}
]";
dynamic blogPosts = JArray.Parse(json);
dynamic blogPost = blogPosts[0];
string title = blogPost.Title;
Console.WriteLine(title);
// Json.NET is awesome!
string author = blogPost.Author.Name;
Console.WriteLine(author);
// James Newton-King
DateTime postDate = blogPost.Date;
Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.
答案 1 :(得分:0)