awancilik awancilik - 4 months ago 9
JSON Question

create array data in json with c#

I am trying to create the following JSON data:

var data = [[1, 27], [2, 34], [3, 51], [4, 48], [5, 55], [6, 65], [7,
61], [8, 70], [9, 65], [10, 75], [11, 57], [12, 59], [13, 62]];


I already try but manually use string builder but I know it is not a good solution, then I create some merge something like this

var bldgNum = new int[] { 1, 2, 5 };
var flatNum = new int[] { 27, 109, 25, 200 };
var address = bldgNum
.Zip(flatNum, (bl, fl) => "[" + bl + ", " + fl.ToString() + "]");


perhaps anyone have a better solution for doing that.

Answer

You could create an array of arrays, and use JavaScriptSerializer to produce a string:

// This creates an array of two-element arrays:
var address = bldgNum
    .Zip(flatNum, (bl, fl) => new[] {bl, fl})
    .ToArray();
// This produces a JSON string that corresponds to your array-of-arrays:
var jss = new JavaScriptSerializer();
var str = jss.Serialize(address);
Comments