Devsined
Devsined

Reputation: 3521

Deserialize a Dynamic JSON Array on C# WebForm

Hi I am generating a JSON on my API that I am trying to use on codebehind C# in my web application but I cannot deserialize well.

My JSON has an object with JSON arrays and the element inside the array are dynamic so I cannot create a fixed class with those items becuase my JSON can have N ITEMS.

{
    "MAINOBJET": [{
        "ITEM1": "23800",
        "ITEM2": "Dahl; Police",
        "ITEM3": "[email protected]"
    },
    {
        "ITEM1": "23802",
        "ITEM2": "Steve ; Police",
        "ITEM3": "[email protected]"
    }]
}

So how can I deserialize it to a DataTable, list or a Dictionary? Thank you

Upvotes: 4

Views: 6485

Answers (1)

MethodMan
MethodMan

Reputation: 18863

here you can do some thing like the following this example should be able to get you started .. replace the structure / example with your Jason Text

lets say that my JSON Script looks like the following

{
    "some_number": 253.541, 
    "date_time": "2012-26-12T11:53:09Z", 
    "serial_number": "SN8675309"
    "more_data": {
        "field1": 1.0
        "field2": "hello JSON Deserializer" 
    }
}

assign you JSON jsonText to a variable and pass it to the following C# Code

using System.Web.Script.Serialization;

var jsonSerialization = new JavaScriptSerializer();
var dictObj = jsonSerialization.Deserialize<Dictionary<string,dynamic>>(jsonText);
Console.WriteLine(dictObj["some_number"]); //outputs 253.541
Console.WriteLine(dictObj["more_data"]["field2"]); //outputs hello JSON Deserializer

Upvotes: 5

Related Questions