我有一个JSON数据(文件附件)。如何使用C#使用LitJSON解析它?我在对它进行反序列化方面有困难。任何帮助都将不胜感激。
{
"vr-sessions" : {
"-KvDNAFD_BxlKEJ958eX" : {
"interview" : "Android",
"questions" : {
"-KvG7BuWu4eI52pq-6uH" : {
"playaudio" : "audio1",
"question" : "Why cannot you run standard Java bytecode on Android?"
},
"-KvG9rxQv5DWJa1EMnhi" : {
"playaudio" : "audio2",
"question" : "Where will you declare your activity so the system can access it?"
}
}
},
"-KvDNOE8YhVdgovxrzrN" : {
"interview" : "DevOps",
"questions" : {
"-KvMPd0v9BXnjYZxFm5Q" : {
"playaudio" : "audio3",
"question" : "Explain what is DevOps?"
},
"-KvMPi24OKeQTp8aJI0x" : {
"playaudio" : "audio4",
"question" : "What are the core operations of DevOps with application development and with infrastructure?"
},
"-KvMPqYxJunKp2ByLZKO" : {
"playaudio" : "audio5",
"question" : "Explain how “Infrastructure of code” is processed or executed in AWS?"
}
}
},发布于 2017-10-15 16:31:00
在添加了几个缺少的大括号并移除最后一个逗号后,您的json似乎是有效的。但是,无法在C#中以破折号开始声明类或成员。不确定如果名称不匹配,LitJson如何能够将json值映射到C#类,除非在用LitJson解析字符串之前替换破折号。
解决方案
在解决方案资源管理器中,右键单击References并执行Add Reference,然后从Assemblies>Framework中选择System.Web.Extensions。
string jsonString = File.ReadAllText("json.txt");
dynamic json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);导航到您要查找的值
string interview = json["vr-sessions"]["-KvDNAFD_BxlKEJ958eX"]["interview"];变量interview获得"Android“值,这与执行以下操作相同:
var sessions = json["vr-sessions"];
string interview = sessions["-KvDNAFD_BxlKEJ958eX"]["interview"];如果您不知道会话名
迭代以获得问题和播放音频值。
foreach (var session in json["vr-sessions"].Values)
{
foreach (var question in session["questions"].Values)
{
Console.WriteLine(question["question"]);
Console.WriteLine(question["playaudio"]);
}
}按位置访问元素:假设您想迭代0..N
var sessions = new List<dynamic>(json["vr-sessions"].Values);
Console.WriteLine(sessions[0]["interview"]);这打印了"Android“,因为在0位置的会话的面试值是"Android”。
https://stackoverflow.com/questions/46756132
复制相似问题