2

I am not a C# programmer, but rather playing with the language from time to time. I wonder, if I have a JSON string which I want to deserialize using JavaScriptSerializer.DeserializeObject, how could I do that. For instance, if I have a JSON:

{
    "Name": "col_name2",
    "Value": [
        {
            "From": 100,
            "To": 200
        },
        {
            "From": 100,
            "To": 200
        }
    ]
}

And I have that JSON string in a variable called sJson:

using System.Web.Script.Serialization;
...

JavaScriptSerializer jss = new JavaScriptSerializer();
Object json = jss.DeserializeObject(sJson);

and now how do I use this Object json variable?

Note: I already know how to do it using System.Web.Script.Serialization.Deserialize<T> method.

vivanov
  • 1,422
  • 3
  • 21
  • 29
  • The result in this case will be a `Dictionary`, where the key for one item will be `"Name"` with a value of "`col_name2"`, another with `"Value"` with a value of `object[]`, the two objects inside the json array. You should create some classes to deserialize into, makes your life a lot easier. – Lasse V. Karlsen Aug 28 '17 at 06:39
  • Thanks. Indeed it works as you say, the only thing is that instead of Object json I have to use dynamic json = jss.DeserializeObject(sJson); and that was what was stopping me. – vivanov Aug 28 '17 at 07:07

2 Answers2

9

Look at this post for Davids Answer:

Deserialize json object into dynamic object using Json.net

You can put it into a dynamic (underlying type is JObject) Then you can than access the information like this:

JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic json = jss.DeserializeObject(sJson);
Console.WriteLine(json["Name"]); // use as Dictionary

I would prefer create a data transfer object (DTO) represent your JSON Structure as a c# class.

vivanov
  • 1,422
  • 3
  • 21
  • 29
Butti
  • 359
  • 2
  • 6
  • It compiles, but at run time it throw an exception: 'System.Collections.Generic.Dictionary' does not cont ain a definition for 'Name'. – vivanov Aug 28 '17 at 06:58
  • Ok, I figured it out: I have to call it like that: Console.WriteLine(json["Name"]); – vivanov Aug 28 '17 at 07:05
2

You could declare new custom classes for this specific case:

public class CustomClass
{
    public string Name { get; set; }
    public List<ValueClass> Value { get; set; }
}

public class ValueClass
{
    public int From { get; set; }
    public int To { get; set; }
}

Then deserialize directly to those classes (the deserializer will automatically map the correct properties):

JavaScriptSerializer jss = new JavaScriptSerializer();
CustomClass json = (CustomClass)jss.Deserialize(sJson, typeof(CustomClass));

Moreover if you have more than 1 items, this is easy as well:

List<CustomClass> json = (List<CustomClass>)jss.Deserialize(sJson, typeof(List<CustomClass>));
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41