I have a JSON data (file attached). How can I parse it using C# using LitJSON? I am having trouble in deserialising it. Any help would be appreciated.
{
"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?"
}
}
},
After adding a couple of missing braces and removing last comma, your json seems to be valid. However there's no way to declare a class or member starting with dash in C#. Not sure how LitJson would be able to map json values to a C# class if names don't match, unless you replace dashes before parsing the string with LitJson.
Workaround
In your Solution Explorer right click References
and do Add Reference
, then from Assemblies->Framework select System.Web.Extensions
.
string jsonString = File.ReadAllText("json.txt");
dynamic json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
Navigate to the value you're looking for
string interview = json["vr-sessions"]["-KvDNAFD_BxlKEJ958eX"]["interview"];
Variable interview
gets value "Android" which is the same as doing this:
var sessions = json["vr-sessions"];
string interview = sessions["-KvDNAFD_BxlKEJ958eX"]["interview"];
If you don't know session names
Iterate to get question and playaudio values.
foreach (var session in json["vr-sessions"].Values)
{
foreach (var question in session["questions"].Values)
{
Console.WriteLine(question["question"]);
Console.WriteLine(question["playaudio"]);
}
}
Access to an element by position: let's say you want to iterate 0..N
var sessions = new List<dynamic>(json["vr-sessions"].Values);
Console.WriteLine(sessions[0]["interview"]);
This prints "Android" as the value of interview for session at position 0 is "Android".