各位!我是新来的。我有这个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 (真)
elements.pages.pageId
因此,我需要根据键/路径检索值,就像Javascript中通常的那样。有线索吗?
泰!
发布于 2017-01-13 20:46:09
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这样做:
ElementsObj tmp = JsonConvert.DeserializeObject<ElementsObj>(jsonString);发布于 2017-01-13 20:41:06
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;https://stackoverflow.com/questions/41643007
复制相似问题