C#简单操作json文件


一、json格式简介

就是键值对形式,{}是对象,[]是数组,相互组合构建。

示例文件Untitled-1.json

{
  "unitinfo": [
    {
      "name": "unit1",
      "bearing": {
        "1": "1,2",
        "2": "3,4",
        "3": "5,6",
        "4": "7,8",
        "5": "9,10",
        "6": "11,12",
        "7": "13,14",
        "8": "15,16"
      },
      "modules": "path1"
    },
    {
      "name": "unit2",
      "bearing": {
        "1": "aaa",
        "2": "bbb",
        "3": "ccc",
        "4": "ddd",
        "5": "eee",
        "6": "fff",
        "7": "fff",
        "8": "fff"
      },
      "modules": "path3"
    }
  ],
    "equipmentinfo":[{
        "name":"a1",
        "model":"patha1"
    }]
}

二、引入Newtonsoft.Json

右击引用,在NuGet程序包中搜索下载

三、读取操作的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"C:\Users\Administrator\source\repos\ConsoleApp2\Untitled-1.json";
            using (StreamReader file=new StreamReader(filepath))
            {
                using (JsonTextReader reader=new JsonTextReader(file))
                {
                    JObject jobj = (JObject)JToken.ReadFrom(reader);
                    Console.WriteLine("最上层对象总数:"+jobj.Count);
                    var j1 = jobj["unitinfo"];//按键值对的用法取键为"unitinfo"的值
                    Console.WriteLine("unitinfo数组长度:"+j1.Count());//JToken对象没有Count属性,但有Count()方法
                    //"unitinfo"的值是一个数组,遍历数组
                    foreach (var item in j1)
                    {
                        Console.WriteLine("组别:"+item["name"]);
                        var ib = item["bearing"];//取键为"bearing"的值
                        Console.WriteLine("bearing值对象内属性的总数:"+ib.Count());////"bearing"的值是对象,也可以遍历,将子对象转成JProperty类型,就可以获取键值name/value
                        foreach (JProperty item2 in item["bearing"]) 
                        {
                            Console.WriteLine("键为"+item2.Name+"值为" + item2.Value);
                        }
                    }
                }
            }         
            Console.ReadKey();
        }
    }
}

运行结果:

四、修改操作

待续...