简体   繁体   中英

Converting a JSON object to dynamic List object without knowing it children structure

I need to produce excel sheet from JSON object. My JSON object is unknown and can be different from call to call. It have a simple structure (same fields in multiple rows).

I want to use the following code.

workSheet.Cells[2, 1].LoadFromCollection(dataList, false);

dataList input is List (dynamic)

Since my JSON is unknown, I can't define a class for this list (params names and types)

My question is How do I convert a JSON object dynamically to List?

for example I have json object with 3 rows to export:

dataJson -> [{"FirstName":"Yaniv","LastName":"Test","Age": 30,"SubmitDate":"2019-10-04"},{....},{....}]   

I need it to be a List dataList -> Count 3

first Item:

Age 30
FirstName "Yaniv"
LastName "Test"
SubmitDate [2019-10-04]

You could deserialise your JSON into a List<Dictionary<string, object>> . For example:

var json = "[{\"FirstName\":\"Yaniv\",\"LastName\":\"Test\",\"Age\": ......]"; 
var data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

Now you can extract some details from this list. So to get the column names:

var columnNames = data.First().Keys.ToList();

And loop around your data like this. This will basically output in CSV format, but it should be enough to modify for your needs:

// Write out the column headers
foreach (var columnName in columnNames)
{
    Console.Write(columnName + ",");
}
Console.WriteLine();

// Write out each element
foreach (var item in data)
{
    foreach (var columnName in columnNames)
    {
        Console.Write(item[columnName] + ",");
    }

    Console.WriteLine();
}

This will give output something like this:

FirstName,LastName,Age,SubmitDate,
Yaniv,Test,30,2019-10-04,
Yaniv,Test,30,2019-10-04,
Yaniv,Test,30,2019-10-04,

If you're using Newtonsoft.Json you can deserialize it into a dynamic structure:

var dyn = JArray.Parse("{jsonhere...}");

Then you can read properties like that:

const string json =
"[{\"prop\": 1, \"test\": \"test!\"}, {\"prop\": 2, \"test\": \"test again!\"}, {\"prop\": 3, \"test\": \"one more!\"}]";

var parsed = JArray.Parse(json);

foreach (var value in parsed)
{
     var prop = value.Value<int>("prop");
     var test = value.Value<string>("test");

     Console.WriteLine($"Prop: [{prop}] | Test: [{test}]");
}

Result output will be:

Prop: [1] | Test: [test!]
Prop: [2] | Test: [test again!]
Prop: [3] | Test: [one more!]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM