Today I specially sorted out how to generate the json array, because I used to be lazy when I needed to use the json array, using i.ToString();
Take a three-dimensional array as an example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.Text.RegularExpressions;
using LitJson;
namespace TestPath
{
class Program
{
static void Main(string[] args)
{
int[,,] a = new int[2, 2, 2];
a[0, 0, 0] = 2;
a[0, 0, 1] = 3;
a[0, 1, 0] = 2;
a[0, 1, 1] = 4;
a[1, 0, 0] = 2;
a[1, 0, 1] = 5;
a[1, 1, 0] = 2;
a[1, 1, 1] = 6;
//声明一个Json对象
JsonData data = new JsonData();
for (int i = 0; i < a.GetLength(0); ++i)
{
//往Json对象里添加索引键i
data.Add(i);
//将data[i]初始化为新的JsonData对象,否则会nullReference
data[i] = new JsonData();
for (int j = 0; j < a.GetLength(1); ++j)
{
//同理,这时候需要往data[i]里添加j的索引键
data[i].Add(j);
data[i][j] = new JsonData();
for (int k = 0; k < a.GetLength(2); ++k)
{
data[i][j].Add(k);
data[i][j][k] = a[i, j, k];
}
}
}
string json = data.ToJson();
//json:[[[2,3],[2,4]],[[2,5],[2,6]]]
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json);
File.WriteAllBytes(@"E:\jjj.json", bytes);
}
}
}
//Ignore unnecessary using, because this project is usually used for testing.
Each time you need to add a new integer index key, you must use the .Add(int) method to add it, so that you can continue to initialize data[i], because data[i] exists.
If it is an index key of a string, you can directly add data[string key] to add key-value pairs.