所以我試圖採用.json文件並在c#中讀取它,然後修改其中一個值,然後刷新.json文件以便更改該值。我知道如何讀取文件以及如何覆蓋文件,但是如何更改文件中某個特定項目的某個特定值?如何在Unity3D中使用LitJson編輯C#中的JSON值?
此腳本的目標是創建一個庫存系統,其餘額可以通過json文件進行記錄。我想使用BalanceChange()函數轉到文件,使用ID變量找到正確的項目,然後相應地更改餘額。
這是我上傳.json腳本:
[
{
"name":"Potion",
"id":1,
"balance":5
},
{
"name":"Neutral Bomb",
"id":2,
"balance": 4
}
]
這裏是我的C#腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using LitJson;
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
public int Balance { get; set; }
public Item(string name1, int id1, int balance1) {
Name = name1;
Id = id1;
Balance = balance1;
}
}
public class InventoryAttempt : MonoBehaviour
{
public static void BalanceChange(string filePath, int ID, int change)
{
string jsonString = File.ReadAllText(Application.dataPath + filePath);
List<Item> itemList = JsonMapper.ToObject<List<Item>>(jsonString);
itemList [ID].Balance += change;
jsonString = JsonMapper.ToJson (itemList).ToString();
File.WriteAllText (Application.dataPath + filePath, jsonString);
}
void Start()
{
BalanceChange ("/Scripts/inventory.json", 1, -1);
}
}
這個腳本是不是出於某種原因的工作。我一直得到這個錯誤:
MissingMethodException: Method not found: 'Default constructor not found...ctor() of Item'.
System.Activator.CreateInstance (System.Type type, Boolean nonPublic) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:368)
System.Activator.CreateInstance (System.Type type) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:254)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ToObject[List`1] (System.String json)
InventoryAttempt.BalanceChange (System.String filePath, Int32 ID, Int32 change) (at Assets/Scripts/InventoryAttempt.cs:26)
InventoryAttempt.Start() (at Assets/Scripts/InventoryAttempt.cs:34)
請發佈您正在談論的代碼。 –
考慮閱讀http://stackoverflow.com/help/how-to-ask以獲得您可以獲得的最佳幫助!如果你想得到更具體的幫助,請延長你的問題,就像@DourHighArch說的那樣! – Maakep