0

我正在尝试使用 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)
4

2 回答 2

1

首先,您的 Json 中的变量名称与您Item班级中的变量名称不匹配。你Item班上的那些都是大写的。

使用 Unity 的JsonUtility.

其次,从这篇文章中获取JsonHelper课程。它允许 Unity序列化和反序列化 Json 数组。JsonUtility

以后不要手动生成 Json,因为会遇到这样的问题。使用 Json 类和一个简单的函数来做到这一点。例如,这个:

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班级:

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);
    }
}

你的ItemItem

[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);
    }
}

笔记:

我删除了获取/设置属性的东西。请删除这些,因为它们必须被删除才能正常工作。此外,[Serializable]被添加到Item类的顶部。请也添加。我建议您在问题下发表“它不起作用”评论之前直接复制和替换这些类......

于 2017-02-10T21:52:56.533 回答
0

首先,您的 json 似乎不是一个有效的数组(不是缺少的[and ].

[
    {
        "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和/或反序列化结果。如果预期的 ID 可能不存在,您可能还想使用 FirstOrDefault 并使用空检查。

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);
    }
}
于 2017-02-10T19:02:19.787 回答