67

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?

desto
  • 1,047
  • 3
  • 14
  • 19
  • Can you use [DynamicJson](http://dynamicjson.codeplex.com/) to prepare the C# objects out of Json strings? – rt2800 Oct 01 '12 at 15:57

5 Answers5

65

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.

AZ.
  • 7,333
  • 6
  • 44
  • 62
  • 1
    @L.B You're right, it was in a hurry. The updated code reads array now. – AZ. Oct 01 '12 at 18:42
  • 1
    Actually, the first solution (before the edits) was the one that worked for me. – desto Oct 01 '12 at 23:34
  • Wow. all the examples I've seen used Serialize/Deserialize functions and it was much more confusing than this. I sure love foreach. – Domino Jul 22 '15 at 15:02
  • In general, you can look at the first character in the string. If it is '[' then use `JArray.Parse`. If it is '{' then use `JObject.Parse`. Otherwise... probably isn't valid JSON. – John Henckel Feb 27 '19 at 21:09
40
json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

c# code: to take only a single value, for example the word "bike".

//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

         dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
         string Text = stuff1[0].hws[2];
         Console.WriteLine(Text);

output:

bike
17

you can try with System.Web.Script.Serialization.JavaScriptSerializer:

var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);
Abel
  • 56,041
  • 24
  • 146
  • 247
Guillaume86
  • 14,341
  • 4
  • 53
  • 53
  • it's available in System.Web.Script.Serialization – Guillaume86 Oct 01 '12 at 15:59
  • I really don't think this serializer would work with dictionaries – Evren Kuzucuoglu Oct 01 '12 at 16:00
  • it does, already used it EDIT: just tested my code with @desto json, works fine :) – Guillaume86 Oct 01 '12 at 16:04
  • Side note: defining a class like @Cuong_Le suggested would also fit here – Guillaume86 Oct 01 '12 at 16:10
  • Well that's quite incredible. I always considered the JavaScriptSerializer class to be an old one, deprecated compared to DataContractJsonSerializer (part of .net 3+ I think), which can use the DataContract framework. I know for sure DataContractJsonSerializer doesn't understand dictionaries so I assumed the older JavaScriptSerializer didn't either. My bad. – Evren Kuzucuoglu Oct 01 '12 at 16:20
  • 1
    No problem, actually JavascriptSeralizer is still used in ASP.NET for WebMethods so it's working better that most people imagine ^^ – Guillaume86 Oct 01 '12 at 16:32
  • 4
    You may need to add the reference `System.Web.Extensions` to your project to access this class. – Chris Stillwell May 03 '17 at 16:05
1

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

Erwin
  • 4,757
  • 3
  • 31
  • 41
1

What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.

So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.

One such example is the one everybody uses: JSON .net

There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.

var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });

now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>> with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.

Note: ValueDescription being this class:

public class ValueDescription
{
    public string Description { get; set; }
    public string Value { get; set; }
}
Evren Kuzucuoglu
  • 3,781
  • 28
  • 51