Implementing general read and write of json data in unity

Using the LitJson plug-in

Used by LitJson

Just drag ListJson.dll into the Unity Assets folder to reference it in the code.
Let's encapsulate Litjson to make it more convenient for Unity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;//Introducing plug-ins
using System.IO;
using System.Text;
public class JsonDataTool
{
    
    public static List<T> GetListFromJson<T>(string path)
    {//Get json data
        string str = File.ReadAllText(Application.dataPath + path, Encoding.GetEncoding("UTF-8"));//Read Json string
        if (str == null) Debug.LogError("Target resource not found:" + path);
        List<T> list = JsonMapper.ToObject<List<T>>(str);//Using the method of Litjson to convert a string into a linked list
        return list;
    }
    public static void SetJsonFromList<T>(string path, List<T> list)//This method is often used in the implementation of archiving
    {//Modify json data
        string jsonstr = JsonMapper.ToJson(list);
        File.WriteAllText(Application.dataPath + path, jsonstr);
    }
}

Save as a dictionary

We hope to access the acquired data through the dictionary, so that the index will be more efficient.

In the game, there are props, equipment, and character dialogue. Their attributes are different. If you have contacted litjson, you will realize that although litjson can automatically encapsulate data, it requires that the attribute name of JSON data correspond to the variable name in the entity class one by one. We use the id of the JSON data as the key of the dictionary and the entity class as the value.

We use a secondary dictionary to access all the data and use the class name of each entity class as the key. What is the value? It is a good choice to use the base class object for unpacking.

We use the generic method GetModelDic() to lazy load the dictionary, but in the code, we can't know what properties of T type, and we can't save its ID as the key value, so we can use the where statement to tell the program that t is a basic entity class (as all json data has the ID attribute), so we can access T.id and save it in the dictionary in the code. When using the getmodel < T > () method, it will first determine whether there is a dictionary of this entity class in the dictionary. If there is no dictionary, it will be generated and unpacked as required.

Basic entity class code

public abstract class Model
{
    public int id;
    public Model(){}
}

json data management class

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

public class JsonDataCenterCL : MonoBehaviour
{
    [Header("The following path is on Assets Path in")]
    public static JsonDataCenterCL instance;
    private void Awake()
    {
        instance = this;
        //Preloaded dictionary

    }
    public string jsonDataFolderPath;
    public Dictionary<string, object> dic = new Dictionary<string, object>();

    public static T GetModelById<T>(int id) where T : Model
    {
        Dictionary<int, T> subdic = GetModelDic<T>();
        if (subdic != null)
        {
            if (!subdic.ContainsKey(id))
            {
                Debug.Log("Non-existent" + id);
                return null;
            }
            return subdic[id];
        }

        else
        {
            Debug.Log("The dictionary is empty.");
            return null;
        }
    }
    public static Dictionary<int, T> GetModelDic<T>() where T : Model
    {
        string classname = typeof(T).ToString();
        if (instance.dic.ContainsKey(classname))
        {

            return instance.dic[classname] as Dictionary<int, T>;
        }

        else
        {

            Dictionary<int, T> subdic = new Dictionary<int, T>();
            List<T> ls = JsonDataTool.GetListFromJson<T>(instance.jsonDataFolderPath + "/" + classname + ".json");
            foreach (var i in ls)
            {
                subdic.Add(i.id, i);
            }

            instance.dic.Add(classname, subdic);
            return subdic;
        }
    }

}

Published 5 original articles, praised 0, visited 24
Private letter follow

Keywords: JSON Unity Attribute encoding

Added by peter.t on Tue, 18 Feb 2020 04:41:18 +0200