desto desto - 2 months ago 8
C# Question

Parse Json string in C#

I'm trying to read a Json string in C#, but I'm having trouble figuring out just how to parse the string into C#. Say I have the following Json string

[
{
"AppName": {
"Description": "Lorem ipsum dolor sit amet",
"Value": "1"
},
"AnotherAppName": {
"Description": "consectetur adipisicing elit",
"Value": "String"
},
"ThirdAppName": {
"Description": "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua",
"Value": "Text"
},
"Application": {
"Description": "Ut enim ad minim veniam",
"Value": "100"
},
"LastAppName": {
"Description": "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat",
"Value": "ZZZ"
}
}
]


I want to parse that into an arraylist or dictionary, using a format like

descriptionList["AppName"] = "Lorem ipsum dolor sit amet";
valueList["AppName"] = "1";


I've been toying around with Json.Net but the examples I've seen don't give me a clear idea of how I should do this. What's the best way to achieve this? Cant this be done like in jQuery, using a foreach statement?

AZ. AZ.
Answer

I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:

EDIT: I changed the code so it supports reading your json file (array)

Code to parse:

void Main()
{
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
    {
        foreach(KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];

            Console.WriteLine(appName);
            Console.WriteLine(description);
            Console.WriteLine(value);
            Console.WriteLine("\n");
        }
    }
}

Output:

AppName
Lorem ipsum dolor sit amet
1


AnotherAppName
consectetur adipisicing elit
String


ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text


Application
Ut enim ad minim veniam
100


LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ

BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.