C# Json文件读取

前言
  • 关于用litjson来解析json格式的文件,我看过两个教程,第一个并没有讲json的语法原理,只讲了怎么使用。第二个很清晰明了说了数组和对象这个概念
  • 但凡是有数组的地方,都可以用list来进行替换
  • JSON跟XML一样是一种是数据格式,都是文本文件
Json语法格式
  • JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。
    • 数据在键值对中
    • 数据由逗号分隔
    • 花括号保存对象
    • 方括号保存数组
  • Json由键/值对构成
  • 值的类型如下
    JSON 值可以是:
    • 数字(整数或浮点数)
    • 字符串(在双引号中)
    • 逻辑值(true 或 false)
    • 数组(在方括号中)
    • 对象(在花括号中)
    • null
  • 简单来说,Json就是对象和数组两种结构,通过不同的组合可以表示很多信息
  • 通过键来取值或者赋值
  • Json里面的属性名需要和对象的相一致
  • Json的根要么是一个数组或者一个对象
JsonData 转化为Json格式字符串
JsonData jd = new JsonData();
jd["Name"] = "myname";
jd["Damage"] = 15;
//打印出来就是Json格式字符串
将Json文本文件转换为list集合【根为数组】
  • 第一种方式 直接转换
  List<Weapon> list = JsonMapper.ToObject<List<Weapon>>(File.ReadAllText("WEAPONAll.txt"));
  • 第二种方式 先获取JsonData数组对象,然后遍历,取键值对,给对象赋值,最后将对象加入到集合中
  JsonData jsond = JsonMapper.ToObject(File.ReadAllText("WEAPONAll.txt"));

            List<Weapon> list = new List<Weapon>();

            for (int i = 0; i < jsond.Count; i++)
            {
                Weapon weapon = new Weapon();
                weapon.Name = jsond[i]["Name"].ToString();
                weapon.Damage = int.Parse(jsond[i]["Damage"].ToString());
                weapon.Duration = int.Parse(jsond[i]["Duration"].ToString());
                list.Add(weapon);
            }
  • 第三种方式 先获得JsonData对象,然后遍历对象数组,将JsonData对象直接转化为相应实体类对象
 JsonData jsond = JsonMapper.ToObject(File.ReadAllText("WEAPONAll.txt"));
            List<Weapon> list = new List<Weapon>();
            for (int i = 0; i < jsond.Count; i++)
            {
                Weapon weapon = JsonMapper.ToObject<Weapon>(jsond[i].ToJson()); //注意这里是转换为Json字符串格式
                list.Add(weapon);
            }
将Json文本文件转换为list集合【 当根是对象时】
   class Weapon
    {

        private List<Weapon> enemy = new List<Weapon>();
        public string Name { set; get; }
        public int Damage { set; get; }
        public int Duration { set; get; }
        public List<Weapon> Enemy { get => enemy; set => enemy = value; }

        public Weapon(string name, int damage, int duration, List<Weapon> list)
        {
            this.Name = name;
            this.Damage = damage;
            this.Duration = duration;
            this.enemy = list;
        }

        public Weapon() { }
        public override string ToString()
        {
            return string.Format("name:{0}-damage{1}-duration{2},listCount{3}", Name, Damage, Duration,Enemy.Count);
        }
    }
  • Json字符串
{
  "Name":"jueshi",
"Damage":21,
"Duration":15,
"Enemy":[{"Name":"rifle","Damage":20,"Duration":10},{"Name":"GongJian","Damage":10,"Duration":10},{"Name":"good","Damage":20,"Duration":10}]
}
  • 转换步骤
 Weapon wea = JsonMapper.ToObject<Weapon>( File.ReadAllText("WEAPONAll.txt"));
            Console.WriteLine(wea.ToString());
            Console.ReadKey(); //输出结果可以注意到List的count为3
转换为Json格式字符串
  • 这个很简单
 string data = JsonMapper.ToJson(weapons);

其它几个例子

  • 嵌套的数组
[
    {
        "Type": [
            {
				"ItemID":1,
                "ItemName": "地基"
            },
            {
				"ItemID":2,
                "ItemName": "墙壁"
            },
            {
				"ItemID":3,
                "ItemName": "门"
            },
            {
				"ItemID":4,
                "ItemName": "窗户"
            }
        ]
    },
	{
        "Type": [
            {
				"ItemID":11,
                "ItemName": "弓箭"
            },
            {
				"ItemID":12,
                "ItemName": "长矛"
            }
        ]
    }
]
  • 一种解析方法
 public List<List<CraftingContentItem>> ByNameGetJsonData(string name)
    {
        List<List<CraftingContentItem>> temp = new List<List<CraftingContentItem>>();
        string jsonStr = Resources.Load<TextAsset>("JsonData/" + name).text;

        JsonData jsonData = JsonMapper.ToObject(jsonStr);
        for (int i = 0; i < jsonData.Count; i++)
        {
            List<CraftingContentItem> tempList = new List<CraftingContentItem>();
            JsonData jd = jsonData[i]["Type"];
            for (int j = 0; j < jd.Count; j++)
            {
                tempList.Add(JsonMapper.ToObject<CraftingContentItem>(jd[j].ToJson()));
            }
            temp.Add(tempList); //一个数组里面包含对象,每个对象又包含一个数组
        }
        return temp;
    }
  • 如果对象里面的某个字符串属性要进行分割
[
    {
        "MapId": 11,
        "MapContents":"0,1,1,1,2,0,0,1,2,1,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0",
		"MapName":"Wooden Bow"
    },
    {
        "MapId": 12,
        "MapContents":"0,0,0,1,2,0,0,0,1,1,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0",
		"MapName":"Wooden Spear"
    }
]
  • 一种解析方式
 private Dictionary<int, CraftingMapItem> LoadMapContents(string name)
    {
        Dictionary<int, CraftingMapItem> temp = new Dictionary<int, CraftingMapItem>();
        string jsonStr = Resources.Load<TextAsset>("JsonData/" + name).text;
        JsonData jsonData = JsonMapper.ToObject(jsonStr);
        for (int i = 0; i < jsonData.Count; i++)
        {
           //取临时数据.
           int mapId = int.Parse(jsonData[i]["MapId"].ToString());
           string tempStr = jsonData[i]["MapContents"].ToString();
           string[] mapContents = tempStr.Split(',');
           string mapName = jsonData[i]["MapName"].ToString();
           //构造对象.
           CraftingMapItem item = new CraftingMapItem(mapId, mapContents, mapName);
           temp.Add(mapId, item);
        }
        return temp;
    }
  • 最平常的解析方式
[
    {
        "ItemName": "Arrow",
        "ItemNum": 64
    },
    {
        "ItemName": "Torch",
        "ItemNum": 1
    },
    {
        "ItemName": "Axe",
        "ItemNum": 1
    }
]
 public List<InventoryItem> GetJsonList(string fileName)
    {
        List<InventoryItem> tempList = new List<InventoryItem>();
        string tempJsonStr = Resources.Load<TextAsset>("JsonData/" + fileName).text;

        //解析JSON.
        JsonData jsonData = JsonMapper.ToObject(tempJsonStr);
        for (int i = 0; i < jsonData.Count; i++)
        {
            InventoryItem ii = JsonMapper.ToObject<InventoryItem>(jsonData[i].ToJson());
            tempList.Add(ii);
        }

        return tempList;
    }
  • 10
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#中,可以使用Json.NET库来读写JSON文件。首先,你需要在项目中引用Json.NET库。然后,你可以通过以下方法读取JSON文件和将数据写入JSON文件: 1. 读取JSON文件: - 首先,使用`File.Exists`方法检查文件是否存在。 - 然后,使用`File.ReadAllText`方法读取文件内容,并将其存储为一个字符串。 - 使用`JsonConvert.DeserializeObject<T>`方法将字符串反序列化为指定的类型(在这个例子中是`ReadJson`类)。 2. 将数据写入JSON文件: - 你可以创建一个用于存储数据的类(在这个例子中是`ReadJson`类)。 - 将数据赋值给该类的属性。 - 使用`JsonConvert.SerializeObject`方法将类对象序列化为JSON字符串。 - 使用`File.WriteAllText`方法将JSON字符串写入文件。 以下是一个示例代码,展示了如何读取和写入JSON文件: ```csharp // 读取JSON文件 private void ReadJsonFile(string fileName) { if (File.Exists(fileName)) { string json = File.ReadAllText(fileName); ReadJson data = JsonConvert.DeserializeObject<ReadJson>(json); // 对读取到的数据进行操作 // 这里是将数据展示在listBox1中 listBox1.Items.Add(AppDomain.CurrentDomain.BaseDirectory); this.y1_value = data.y1_value; this.y2_value = data.y2_value; this.y3_value = data.y3_value; this.y4_value = data.y4_value; this.y5_value = data.y5_value; this.y6_value = data.y6_value; this.y7_value = data.y7_value; this.y8_value = data.y8_value; this.y9_value = data.y9_value; List<List<int>> yValues = new List<List<int>>() { y1_value, y2_value, y3_value, y4_value, y5_value, y6_value, y7_value, y8_value, y9_value }; for (int i = 0; i < yValues.Count; i++) { string prefix = $"y{i + 1}"; string line = string.Join(" ", yValues[i]); listBox1.Items.Add($"{prefix}: {line}"); } } } // 写入JSON文件 private void WriteJsonFile(string fileName) { ReadJson data = new ReadJson() { y1_value = new List<int>() { 1, 2, 3 }, y2_value = new List<int>() { 4, 5, 6 }, y3_value = new List<int>() { 7, 8, 9 }, // 其他数据... }; string json = JsonConvert.SerializeObject(data); File.WriteAllText(fileName, json); } ``` 请注意,你需要根据自己的需求调整代码中的类和属性名称。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值