gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:49:21 25 4
gpt4 key购买 nike

我正在进行文字冒险,每当玩家输入“拿起铁剑”或其他任何内容时,我都需要能够将铁剑从存放它的房间内的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com