在回答我几天前提出的一个问题时,我试图让自己伸展一点,然后做一些我之前并没有真正专注的事情.我已经做了一些搜索(无论是在这里,还是在一般情况下),但是找不到我希望实现的答案(甚至是合理的提示)(尽管有些事情很接近).
基本上,我正在尝试使用Json.NET library对谷歌Chrome书签文件的数据进行反序列化(但是,如果有更好的选择,我就是全部 – 这个库的文档在某些地方有点令人困惑).我对下一步采取的措施感到困惑,主要是因为习惯了PHP对JSON数据的精彩处理(使用json_decode()),允许单个函数调用,然后是简单的关联数组访问.
库(Json.NET)希望我指定一个可以将JSON数据反序列化的Object类型,但鉴于Bookmarks文件本身的格式,我不确定如何构建这样的Object.格式类似于:
{ "roots": { "bookmark_bar": { "children": [ { "children": [ { "date_added": "12880758517186875","name": "Example URL","type": "url","url": "http://example.com" },{ "date_added": "12880290253039500","name": "Another URL","url": "http://example.org" } ],"date_added": "12880772259603750","date_modified": "12880772452901500","name": "Sample Folder","type": "folder" },{ "date_added": "12880823826333250","name": "Json.NET","url": "http://james.newtonking.com/pages/json-net.aspx"; } ],"date_added": "0","date_modified": "12880823831234250","name": "Bookmarks bar","type": "folder" },"other": { "children": [ ],"date_modified": "0","name": "Other bookmarks","type": "folder" } },"version": 1 }
现在,在PHP中,我更习惯于按照以下方式做一些事情,以获得我想要的数据,最后得到’Json.NET’:
$data['roots']['bookmark_bar']['children'][0]['name'];
我可以简单地计算出要创建的对象来表示数据(类似于根对象,然后是书签列表对象,最后是单个书签对象) – 但我真的不确定如何实现它们,然后让库正确反序列化到相关对象.
任何可以提供的建议将不胜感激.
解决方法
没有必要声明反映json结构的类型:
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using System; class Program { static void Main(string[] args) { string json = @" { ""roots"": { ""bookmark_bar"": { ""children"": [ { ""children"": [ { ""date_added"": ""12880758517186875"",""name"": ""Example URL"",""type"": ""url"",""url"": ""http://example.com"" },{ ""date_added"": ""12880290253039500"",""name"": ""Another URL"",""url"": ""http://example.org"" } ],""date_added"": ""12880772259603750"",""date_modified"": ""12880772452901500"",""name"": ""Sample Folder"",""type"": ""folder"" },{ ""date_added"": ""12880823826333250"",""name"": ""Json.NET"",""url"": ""http://james.newtonking.com/pages/json-net.aspx"" } ],""date_added"": ""0"",""date_modified"": ""12880823831234250"",""name"": ""Bookmarks bar"",""type"": ""folder"" },""other"": { ""children"": [ ],""date_modified"": ""0"",""name"": ""Other bookmarks"",""type"": ""folder"" } },""version"": 1 } "; using (StringReader reader = new StringReader(json)) using (JsonReader jsonReader = new JsonTextReader(reader)) { JsonSerializer serializer = new JsonSerializer(); var o = (JToken)serializer.Deserialize(jsonReader); var date_added = o["roots"]["bookmark_bar"]["children"][0]["date_added"]; Console.WriteLine(date_added); } }