C#生成Json的多維陣列
阿新 • • 發佈:2019-01-27
今天特意整理了下json陣列如何生成,因為以前需要用到json陣列的時候都偷懶,使用i.ToString();
先拿一個三維陣列來舉例:
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); } } }
//忽略不必要的using,因為這個工程通常是拿來測試的。
其中每次需要新增新的整形索引鍵時,必須用.Add(int)方法來新增,這樣才可以繼續初始化data[i],因為data[i]是存在的。
如果是字串的索引鍵,則可以直接data[string key]來增加鍵值對。