-1

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.

awancilik
  • 135
  • 1
  • 1
  • 9
  • 2
    Possible duplicate of [How to convert c# arrays to JSON with one array item propety value set as reference to item from another](http://stackoverflow.com/questions/19953335/how-to-convert-c-sharp-arrays-to-json-with-one-array-item-propety-value-set-as-r) – demo Jul 22 '16 at 14:49
  • Possible duplicate of [How to create JSON string in C#](http://stackoverflow.com/questions/1056121/how-to-create-json-string-in-c-sharp) –  Jul 22 '16 at 14:49

2 Answers2

1

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);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • nice, thanks for the enlightment, so basically my solution is create an array lets say an array a and array b, then create an array of two-element arrays like you write in the answer then I convert not in JavaScriptSerializer() but I do convert in JsonConvert.SerializeObject(address); – awancilik Jul 22 '16 at 15:09
  • @awancilik That's right, `JsonConvert` works very well, too. – Sergey Kalinichenko Jul 22 '16 at 15:14
0

You can also use Newtonsoft.Json library (you can get it from NuGet). For your example something like this should solve your problem.

var result = new List<int[]> {new[] {1, 27}, new[] {2, 34}, new int[] {3, 51}};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(result);
ilker
  • 166
  • 2
  • 3