2015/10/26

C#.Net Json.Net 讀/寫檔案

Json.Net目前僅支援到.Net 4.0,有需要的朋友可以參考一下Json.Net官方文件

輸出結果:

{"Test":[{"number":1},{"number":2},{"number":3},{"number":4},{"number":5},{"number":6},{"number":7},{"number":8},{"number":9},{"number":10}]}

讀取結果:
Test
number
1
number
2
number
3
number
4
number
5
number
6
number
7
number
8
number
9
number
10



Code:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace TestProject
{
    public partial class Form1 : Form
    {
        private readonly String PATH = String.Format(@"{0}\test.txt", Directory.GetCurrentDirectory());

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //JSON寫入到檔案
            using (StringWriter sw = new StringWriter())
            {
                using (JsonTextWriter writer = new JsonTextWriter(sw))
                {
                    //建立物件
                    writer.WriteStartObject();

                    //物件名稱
                    writer.WritePropertyName("Test");

                    //建立陣列
                    writer.WriteStartArray();
                    for (int index = 1; index <= 10; index++)
                    {
                        //建立物件
                        writer.WriteStartObject();
                        //設定屬性名稱
                        writer.WritePropertyName(String.Format("number", index));
                        //設定值
                        writer.WriteValue(index);
                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                    writer.Flush();
                    writer.Close();
                    sw.Flush();
                    sw.Close();

                    //將文字寫入該檔案
                    File.WriteAllText(PATH, sw.ToString(), Encoding.UTF8);
                }
            }

            //讀取JSON檔案
            using (StreamReader sr = new StreamReader(PATH, Encoding.UTF8))
            {
                using (JsonTextReader reader = new JsonTextReader(sr))
                {
                    while (reader.Read())
                        if (reader.Value != null)
                            Console.WriteLine(reader.Value.ToString());
                    //讀取Int
                    //reader.ReadAsInt32().Value


                    //結束讀取
                    reader.Close();
                    sr.Close();
                }
            }
        }

    }
}



除了可以取得String的型態,也可透過JsonTextReader的ReadAsXXX().Value來取得不同型態的資料