I am trying to create =>
{
"Data1":{
"DataListOne": [0, 1],
"DataListTwo": [1, 0, 0, 0]
},
"Data2":{
"DataListOne": [1, 0],
"DataListTwo": [0, 0, 0, 1]
},
"Data-n" : {
"DataListOne": [1, 0],
"DataListTwo": [0, 1, 0, 0]
}
}
List dynamically that starting from Data1 to Data-n that is not specified at which point i need to stop that List and also want Two List (DataListOne, DataListTwo) inside Data1 to Data-n.
I am not getting how to create List Dynamically from Data1 to Data-n and also the Two List (DataListOne, DataListTwo) inside Dynamic List from Data1 to Data-n
Please Help Me With This.
I'd use Json.NET for this - it lets you build up the JSON dynamically:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
var pairs = new List<ListPair>
{
new ListPair
{
DataListOne = { 0, 1 },
DataListTwo = { 1, 0, 0, 0 }
},
new ListPair
{
DataListOne = { 1, 0 },
DataListTwo = { 0, 0, 0, 1 }
},
new ListPair
{
DataListOne = { 1, 0 },
DataListTwo = { 0, 1, 0, 0 }
},
};
JObject json = CreateJson(pairs);
Console.WriteLine(json);
}
static JObject CreateJson(List<ListPair> pairs)
{
return new JObject(pairs.Select(
(pair, index) => new JProperty("Data" + (index + 1),
JObject.FromObject(pair))));
}
class ListPair
{
public List<int> DataListOne, DataListTwo;
public ListPair()
{
DataListOne = new List<int>();
DataListTwo = new List<int>();
}
}
}
On the other hand, I think it would be cleaner to just create an array in the JSON rather than having the names generated dynamically.
See more on this question at Stackoverflow