0

我要做的是将我保存在 litjson 文件中的数据以正确的格式添加到列表中。所以我可以稍后在游戏中将其称为图标。这是代码,因此应该很容易重新创建以测试我遇到的问题。

JsonIcons班级:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class JsonIcons {

    public string IconName;//Shows the icon Name in the list
    public int IconID;// Shows the Icon ID in the list
    public Sprite AssignIcon;

    public JsonIcons(string Name, int ID )
    {
        IconName = Name;
        IconID = ID;
    }

    public JsonIcons()
    {
    }
}

JsonTest班级:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.IO;

//This class that does the saving
public class JsonTest : MonoBehaviour {

    public List<JsonIcons> JIcon = new List<JsonIcons>();
    public JsonData JCD;

    protected JsonIcons KZ, TestTK;

    public void Start()
    {
        TestTK = new JsonIcons("Kagami", 40);
        KZ = new JsonIcons("Magic", 0);

        JIcon.Add(TestTK); //Add things to the list to be save
        JIcon.Add(KZ);

        JCD = JsonMapper.ToJson(JIcon);
        //This is where I saved the things inside the JIcon list to a Json file
        File.WriteAllText(Application.dataPath + "/JsonSaveTest.json", JCD.ToString());
        //Debug.Log(JCD);
    }
}

JsonReadTest班级:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using LitJson;

public class JsonReadTest : MonoBehaviour {

    public List<JsonIcons> ReadSJ = new List<JsonIcons>();

    private string JString;
    public JsonData IconData;

    // Use this for initialization
    void Start () 
    {
        //Trying to get this file to load in the correct format inside the ReadSJ list
        JString = File.ReadAllText(Application.dataPath + "/JsonFiles/JsonSaveTest.json");
        IconData = JsonMapper.ToObject(JString);
    }
}
4

1 回答 1

0

您可以创建一个名为 JsonIconList 的类,该类仅包含一个 List(顺便说一下,您应该将 JsonIcons 重命名为 JsonIcon,因为它代表一个项目)。然后您可以使用 JsonMapper 类轻松反序列化它。

另一种方法是有一个像这样的通用包装类

[Serializable]
private class ListWrapper<T>
{
    public List<T> Items;
}

然后创建一个辅助方法

public static class JsonHelper
{
    public static List<T> ToList<T>(string json)
    {
        ListWrapper<T> wrapper = JsonMapper.ToObject<ListWrapper<T>>(json);
        return wrapper.Items;
    }
}

并像这样使用它

List<JsonIcon> icons = JsonHelper.ToList<JsonIcon>(jsonString);
于 2017-05-16T13:54:45.767 回答