【问题标题】:Unity 3d - Trouble deserialising a JsonUnity 3d - 反序列化 Json 的麻烦
【发布时间】:2018-02-10 17:21:50
【问题描述】:

所以,我有一个包含两个类成员的 Json 文件,如下所示:

{
"Item": 
 [

    {
        "itemID": 1,
        "name": "Apple",
        "description": "fluff",
        "value": 2,
        "weight": 50,
        "quantity": 5,
        "type": "Craftable",
        "favourited": false,
        "rt": null
    },
    {
        "itemID": 2,
        "name": "Star Shard",
        "description": "fluff",
        "value": 2,
        "weight": 50,
        "quantity": 5,
        "type": "Craftable",
        "favourited": false,
        "rt": null
    }
] }

我尝试在运行时将其解析为 C# 中的列表/数组/或该类的成员,但它失败了。

这是c#中的代码:

[System.Serializable]

公共类 Item_Pickup : MonoBehaviour { 公共字符串文件路径;

public class Item
{

    public int itemID;
    public string name;
    public string description;
    public int value;
    public int weight;
    public int quantity;
    public string type;
    public bool favourited;
    public RectTransform rt;

    public static Item CreateFromJson(string jsonstring)
    {
        return JsonUtility.FromJson<Item>(jsonstring);
    }
    void start() 
    {

        filepath = Path.Combine(Application.streamingAssetsPath, "Json1.json");
        StreamReader Test = new StreamReader(filepath);
        string e = Test.ReadToEnd().Trim();
        Item[] items = JsonUtility.FromJson<Item[]>(e);

        foreach(var item in items)
        {
        print(item.name);
        //returns null, the list contains no data. 
        }
    } }

上面的代码为数组返回了一个 null 值,所以它似乎没有正确读取 json。

如果我将 json 设置为包含一个类成员,而不是作为数组的一部分,我可以轻松地读取该类并在运行时将其分配给 c# 脚本中的一个类。

我是否遗漏了一些关于如何正确读取数组内具有多个类成员的 json 文件的基本知识?我查看了 Newtonsoft,但当前版本的 Unity 似乎不支持它。

【问题讨论】:

  • 我认为您需要将数组设为顶层。所以不要输入{ "Item": [....,而是输入[ {....}。目前你的顶层是一个名为Item的属性。
  • JsonUtility.FromJson&lt;Item[]&gt;(e) ,不,您的顶级对象是包含Item[] 的类,例如public class Root{ public Item[] Item; }

标签: c# arrays json list


【解决方案1】:

我认为问题在于 RectTransform,Json 不支持它,因此在淡化时无法识别。

尝试将其设为vector3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2022-01-20
    • 2023-03-09
    • 2018-12-18
    相关资源
    最近更新 更多