Deserialize a Dynamic JSON Array on C# WebForm

天大地大妈咪最大 提交于 2019-12-13 13:16:12

问题


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": "test@test.net"
    },
    {
        "ITEM1": "23802",
        "ITEM2": "Steve ; Police",
        "ITEM3": "test2@test.net"
    }]
}

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


回答1:


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


来源:https://stackoverflow.com/questions/14044109/deserialize-a-dynamic-json-array-on-c-sharp-webform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!