c# - 如何在 C# 中编辑 json 文件?

标签 c# json

我正在进行文字冒险,每当玩家输入“拿起铁剑”或其他任何内容时,我都需要能够将铁剑从存放它的房间内的 JSON 数组中取出。

{
Rooms: [
    {
        id: "PizzaShop1",
        name: "Pizza Shop",
        description: "in a nice warm pizza shop that smells of garlic.",
        items: [
            {
                id: "HawaiianPizza1",
                name: "Hawaiian Pizza",
                description: "a pizza topped with ham and pineapple",
                strengthMod: 0,
                toughnessMod: 0
            },
            {
                id: "MeatloversPizza1",
                name: "Meatlovers Pizza",
                description: "a pizza topped with lots of meat",
                strengthMod: 0,
                toughnessMod: 0
            }
        ],
        entities: [
            {
                name: "Pizza Chef",
                description: "an italian man",
                friendly: true
            },
            {
                name: "Mouse",
                description: "a pesky mouse",
                friendly: false
            }
        ],
        northExit: "",
        southExit: "Road1",
        eastExit: "",
        westExit: ""
    },     
    {
        id: "Road1",
        name: "Road",
        description: "on a town road",
        items: [
            {
                id: "IronSword1",
                name: "Iron Sword",
                description: "a battered but usable sword",
                strengthMod: 2,
                toughnessMod: 0
            }
        ],
        entities: [],
        northExit: "PizzaShop1",
        southExit: "",
        eastExit: "",
        westExit: ""
    }
]
}

这是我的 C# 代码:

                else if (s.Contains(" pick up "))
            {
                String newJson = "";
                s = s.Replace(" the ", " ");
                s = s.Replace(" pick ", " ");
                s = s.Replace(" up ", " ");
                String[] Words = s.Split(' ');
                foreach (String word in Words)
                {
                    if (word != Words[1])
                    {
                        Words[1] = Words[1] + " " + word;
                        Words[1] = Words[1].Replace("  ", " ");
                        Words[1] = Words[1].Trim();
                    }
                }
                using (StreamReader sr = new StreamReader("TAPResources/map.json"))
                {
                    String json = sr.ReadToEnd();
                    dynamic array = JsonConvert.DeserializeObject(json);
                    foreach (var rooms in array["Rooms"])
                    {
                        foreach (var item in rooms["items"])
                        {
                            String itm = (String)item["name"];
                            PrintMessage("Words: " + Words[1]);
                            PrintMessage("Item Name: " + itm.ToLower());
                            if (Words[1] == itm.ToLower())
                            {
                                rooms["items"].Remove(item);
                            }
                        }
                    }
                    newJson = (String)JsonConvert.SerializeObject(array);
                }
                File.WriteAllText("TAPResources/map.json", newJson);
            }

行:

rooms["items"].Remove(item);

报错,因为我不能在循环内编辑数组。通常我会通过将值添加到另一个数组,然后遍历该数组以从初始数组中删除来解决这个问题,但我不知道如何为该变量类型创建一个数组。

最佳答案

好的,我们开始吧,理想情况下,建议使用定义明确的对象(类),无论如何,使用动态对象的情况处理速度较慢:

动态数组 = GetRooms();

    foreach (var rooms in array["Rooms"])
    {
        List<object> list = new List<object>();
        foreach (var item in rooms["items"])
        {
            string itm = (string) item["name"];
            if (!"hawaiian pizza".Equals(itm.ToLower()))
            {
                list.Add(item);
            }
        }
        //u can use this 
        //from rooms in array["Rooms"] select rooms where (true something)
        //or what I did case I'm lazy
        //Newtonsoft.Json.Linq.JToken transfor or you can use linq to dow whatever 
        rooms["items"] = JsonConvert.DeserializeObject<JToken>(JsonConvert.SerializeObject(list.ToArray()));
    }
    Console.Write(JsonConvert.SerializeObject(array));

关于c# - 如何在 C# 中编辑 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36784849/

相关文章:

javascript - 断点没有在 javascript 文件中命中

c# - Linux/Mono 上的 YSOD 故障排除

c# - 基于当前用户的 "Role"动态构建 ASP.NET MVC 母版页菜单

php - array_map 和 array_unique 技术将 json 数据破坏到应用程序

json - 无法访问最初作为 JSON 对象发送的字符串(即 [ object Object ])内的数据

java - 如何获取json数组中子数组的值

javascript - 无法读取 JSON 字符串

jquery - JSON问题中的Rails HTML编码

C# Excel - 将每个工作表保存到一个新工作簿

c# - 如何使用 LINQ 选择一个对象?