简体   繁体   English

Unity 3D-麻烦反序列化Json

[英]Unity 3d - Trouble deserialising a Json

So, I have a Json file that contains two class members, as shown below: 因此,我有一个包含两个类成员的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
    }
] }

I try to parse it into a list/array/or a member of that class inside C# at runtime, but it fails. 我尝试在运行时将其解析为C#中的列表/数组/或该类的成员,但失败。

Here is the code in c#: 这是c#中的代码:

[System.Serializable]

public class Item_Pickup : MonoBehaviour { public string filepath; 公共类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. 
        }
    } }

The above code returns a value of null for the array, so it seems it isn't reading the json correctly. 上面的代码为该数组返回null值,因此似乎无法正确读取json。

If I set the json up to contain one class member, not as part of an array, I can easily read the class and assign it to a class in the c# script at runtime. 如果我将json设置为包含一个类成员,而不是作为数组的一部分,则可以在运行时轻松读取该类并将其分配给c#脚本中的一个类。

Am I missing something fundamental in how to correctly read a json file with multiple class members inside of an array? 我是否缺少一些基本知识,无法正确读取数组中具有多个类成员的json文件? I looked at Newtonsoft, but it seems that isn't supported in the current version of Unity. 我看了看Newtonsoft,但在当前版本的Unity中似乎不支持该功能。

I think the issue is with RectTransform, Json doesn't support it thus not identifying when desalinizing. 我认为问题出在RectTransform上,Json不支持它,因此在脱盐时无法识别。

Try making it vector3 尝试使其成为vector3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM