我正在進行一段文字冒險,當玩家輸入「拿起鐵劍」或其他任何東西時,我需要能夠將JSON陣列中的鐵劍拿出來放在保存的房間內。如何編輯C#中的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);
給出了一個錯誤,因爲我不能編輯循環內的數組。通常我會通過將值添加到另一個數組來解決此問題,然後遍歷該數組以從初始數組中刪除,但我不知道如何爲該變量類型創建數組。
的可能的複製[讀取並解析在C#JSON文件(http://stackoverflow.com/questions/13297563/read-and-parse-a-json-file-in-c-sharp) – Mostafiz
不是重複的,我已經閱讀過它,它根本沒有幫助我。 – Towja
你將不得不對'JsonConvert.SerializeObject(array);'的結果做一些事情,比如把它寫回你的json文件。 –