大家!我是Xamarin的新手。我有这个 json 文件...
{
"debug":true,
"sequence":[
"p1"
],
"pages":[
{
"pageId":"p1",
"type":"seq",
"elements":[
{
"type":"smallVideo",
"width":300,
"height":300,
"top":0,
"left":0,
"file":"xxx.mp4"
}
]
}
],
"index":[
{
"width":300,
"height":300,
"top":0,
"left":0,
"goTo":"p1"
}
]
}
这是我的简单代码...
using Newtonsoft.Json;
JObject elements = JObject.Parse(File.ReadAllText("elements.json"));
Console.WriteLine(elements);
好的,我可以在输出屏幕上看到整个 JSON 文件。好。。。但我想像javascript一样读取任何值,示例...
elements.debug (true)
elements.pages[0].pageId
因此,我需要像在 Javascript 中一样根据键/路径检索值。有什么线索吗?
泰!
C# 与 js 略有不同,这里需要声明对象。在您的情况下,您需要创建名为 ElementsObj 的新类,您的对象将是此类实例:
public class ElementsObj
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
将来使用 http://json2csharp.com/从 JSON 文件生成类。
稍后,您可以将 JSON 反序列化为此对象。我建议Newtonsoft lib这样做:
ElementsObj tmp = JsonConvert.DeserializeObject<ElementsObj>(jsonString);
1) 选项创建一个反映您的 JSON 结构的object
:
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
public class MyObject
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
MyObject parsed = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("elements.json"));
var debug = parsed.debug;
2) 使用dynamic
的选项
dynamic results = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("elements.json"));
var debug = dynamic.debug;