如何使用 LitJson 编辑一个 class 的多个实例的单个属性,所有实例都存储在一个 json 文件中?
How do I use LitJson to edit single attributes of multiple instances of one class all stored in one json file?
我正在尝试使用 json 文件创建库存系统。基本上,我有我的 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);
}
}
在我的 c# 文件中,我想访问单个项目,比如说中性炸弹项目。我怎样才能进入并编辑中性炸弹的余额?我想使用项目 ID 来告诉要编辑的对象。我想创建一个列表,其中每个元素都是存储在 Json 文件中的项目之一,但我不确定如何将它们分开。我该怎么办?
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)
首先,您的 json 似乎不是有效数组(不是缺少的 [
和 ]
。
[
{
"name":"Potion"
"id":1,
"balance":7
},
{
"name":"Neutral Bomb",
"id":2,
"balance": 4
}
]
此外,我会遵循命名约定并以大写字符开头的属性。
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
public int Balance { get; set; }
public Item()
{
}
public Item(string name1, int id1, int balance1)
{
Name = name1;
Id = id1;
Balance = balance1;
}
}
下面的代码应该可以满足您的需求,但根据您的项目范围,效率可能会非常低。您可能要考虑缓存 jsonString
and/or 反序列化结果。您可能还想使用 FirstOrDefault 并在其预期 ID 可能不存在时使用 null 检查。
public class InventoryAttempt : MonoBehaviour
{
public static Item JsonToItem(string filePath, int itemID)
{
string jsonString = File.ReadAllText(Application.dataPath + filePath);
return JsonMapper.ToObject<List<Item>>(jsonString).First(x => x.Id == itemID);
}
void Start()
{
var item = JsonToItem("/Scripts/inventory.json", 1);
}
}
首先,您Json中的变量名与您Item
class中的变量名不匹配。你的Item
class里面的都是大写的
使用Unity的JsonUtility
.
其次,从post得到JsonHelper
class。它允许 Unity 的 JsonUtility
序列化和反序列化 Json 数组。
以后不要手动生成Json,因为你会运行遇到这样的问题。使用 Json class 和一个简单的函数来做到这一点。例如,这个:
void generateJson()
{
Item[] item = new Item[2];
item[0] = new Item();
item[0].Name = "Potion";
item[0].Id = 1;
item[0].Balance = 5;
item[1] = new Item();
item[1].Name = "Neutral Bomb";
item[1].Id = 2;
item[1].Balance = 4;
string value = JsonHelper.ToJson(item, true);
Debug.Log(value);
}
将生成这个:
{
"Items": [
{
"Name": "Potion",
"Id": 1,
"Balance": 5
},
{
"Name": "Neutral Bomb",
"Id": 2,
"Balance": 4
}
]
}
没有错误。那是有效的 json.
解决方法:
InventoryAttempt
class:
public class InventoryAttempt
{
public static void BalanceChange(string filePath, int ID, int change)
{
//Load Data
string jsonString = File.ReadAllText(Application.dataPath + filePath);
Item[] item = JsonHelper.FromJson<Item>(jsonString);
//Loop through the Json Data Array
for (int i = 0; i < item.Length; i++)
{
//Check if Id matches
if (item[i].Id == ID)
{
Debug.Log("Found!");
//Increment Change value?
item[i].Balance += change;
break; //Exit loop
}
}
//Convert to Json
string newJsonString = JsonHelper.ToJson(item);
//Save
File.WriteAllText(Application.dataPath + filePath, newJsonString);
}
}
你的Item
classItem
.
[Serializable]
public class Item
{
public string Name;
public int Id;
public int Balance;
public Item()
{
}
public Item(string name1, int id1, int balance1)
{
Name = name1;
Id = id1;
Balance = balance1;
}
}
测试脚本:
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
InventoryAttempt.BalanceChange("/Scripts/inventory.json", 1, 1);
}
}
注:
我删除了 get/set 属性 东西。请删除这些,因为必须删除它们才能正常工作。此外,[Serializable]
被添加到 Item
class 的顶部。请添加 as-well。 我建议您在问题...
下发表"it doesn't work"评论之前直接复制并替换classes
我正在尝试使用 json 文件创建库存系统。基本上,我有我的 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);
}
}
在我的 c# 文件中,我想访问单个项目,比如说中性炸弹项目。我怎样才能进入并编辑中性炸弹的余额?我想使用项目 ID 来告诉要编辑的对象。我想创建一个列表,其中每个元素都是存储在 Json 文件中的项目之一,但我不确定如何将它们分开。我该怎么办?
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)
首先,您的 json 似乎不是有效数组(不是缺少的 [
和 ]
。
[
{
"name":"Potion"
"id":1,
"balance":7
},
{
"name":"Neutral Bomb",
"id":2,
"balance": 4
}
]
此外,我会遵循命名约定并以大写字符开头的属性。
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
public int Balance { get; set; }
public Item()
{
}
public Item(string name1, int id1, int balance1)
{
Name = name1;
Id = id1;
Balance = balance1;
}
}
下面的代码应该可以满足您的需求,但根据您的项目范围,效率可能会非常低。您可能要考虑缓存 jsonString
and/or 反序列化结果。您可能还想使用 FirstOrDefault 并在其预期 ID 可能不存在时使用 null 检查。
public class InventoryAttempt : MonoBehaviour
{
public static Item JsonToItem(string filePath, int itemID)
{
string jsonString = File.ReadAllText(Application.dataPath + filePath);
return JsonMapper.ToObject<List<Item>>(jsonString).First(x => x.Id == itemID);
}
void Start()
{
var item = JsonToItem("/Scripts/inventory.json", 1);
}
}
首先,您Json中的变量名与您Item
class中的变量名不匹配。你的Item
class里面的都是大写的
使用Unity的JsonUtility
.
其次,从JsonHelper
class。它允许 Unity 的 JsonUtility
序列化和反序列化 Json 数组。
以后不要手动生成Json,因为你会运行遇到这样的问题。使用 Json class 和一个简单的函数来做到这一点。例如,这个:
void generateJson()
{
Item[] item = new Item[2];
item[0] = new Item();
item[0].Name = "Potion";
item[0].Id = 1;
item[0].Balance = 5;
item[1] = new Item();
item[1].Name = "Neutral Bomb";
item[1].Id = 2;
item[1].Balance = 4;
string value = JsonHelper.ToJson(item, true);
Debug.Log(value);
}
将生成这个:
{
"Items": [
{
"Name": "Potion",
"Id": 1,
"Balance": 5
},
{
"Name": "Neutral Bomb",
"Id": 2,
"Balance": 4
}
]
}
没有错误。那是有效的 json.
解决方法:
InventoryAttempt
class:
public class InventoryAttempt
{
public static void BalanceChange(string filePath, int ID, int change)
{
//Load Data
string jsonString = File.ReadAllText(Application.dataPath + filePath);
Item[] item = JsonHelper.FromJson<Item>(jsonString);
//Loop through the Json Data Array
for (int i = 0; i < item.Length; i++)
{
//Check if Id matches
if (item[i].Id == ID)
{
Debug.Log("Found!");
//Increment Change value?
item[i].Balance += change;
break; //Exit loop
}
}
//Convert to Json
string newJsonString = JsonHelper.ToJson(item);
//Save
File.WriteAllText(Application.dataPath + filePath, newJsonString);
}
}
你的Item
classItem
.
[Serializable]
public class Item
{
public string Name;
public int Id;
public int Balance;
public Item()
{
}
public Item(string name1, int id1, int balance1)
{
Name = name1;
Id = id1;
Balance = balance1;
}
}
测试脚本:
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
InventoryAttempt.BalanceChange("/Scripts/inventory.json", 1, 1);
}
}
注:
我删除了 get/set 属性 东西。请删除这些,因为必须删除它们才能正常工作。此外,[Serializable]
被添加到 Item
class 的顶部。请添加 as-well。 我建议您在问题...