Unity creates and parses json

I looked through the previous blog today and found that I wrote several articles about loading json. Today I just have time to summarize the contents of the previous articles, and then add some new content.
Plug-ins for loading json that can be used in unity include: JsonUtility (included with unity), LitJson, Newtonsoft, etc. Plug-ins have their own advantages, so I won't list them one by one. I'm used to using the json plug-in that comes with unity, which is enough for now.
There are two methods when creating a json file, the first is handwriting, and the second is code generation.
The first method is not recommended, but in case you use it, you must be careful not to open the json file with the notebook that comes with windows . When saving the file with the notebook that comes with windows, it will add the file type at the beginning of the file by default, and it is hidden. In this way, an error will always be reported when loading the json file. Using the plug-in that comes with unity will not prompt where the error is, but using other plug-ins will prompt. After this problem occurs, open it with notepad++, and then change the encoding format. The utf-8 saved with notepad is utf-8-bom. If we change it to utf-8, there will be no problem.
The second method is to create a json file with code. During the creation process, several issues need to be paid attention to: the subclass used to create json needs to be serialized, and the properties need to be initialized. I will use this method as an example later.
The last point, no matter what platform is loaded using UnityWebRequest, so no matter which platform, json data can be loaded.
The following is an example:
1. The code creates a json file:

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

/// <summary>
/// 用代码获取根目录下子节点的位置信息,然后保存在json文件中
/// </summary>
public class CreateJson : MonoBehaviour
{
    
    
    private void Start()
    {
    
    
        ModelInfoRoot modelInfoRoot = new ModelInfoRoot();

        if (transform.childCount > 0)
        {
    
    
            for (int i = 0; i < transform.childCount; i++)
            {
    
    
                var vchild = transform.GetChild(i);
                ModelInfo info = new ModelInfo();
                info.Name = vchild.name;
                info.localPos = vchild.localPosition;
                info.localRos = vchild.localRotation.eulerAngles;
                info.localScale = vchild.localScale;
                modelInfoRoot.ModelInfos.Add(info);
            }
        }

        var vbasePath = Path.Combine(Application.streamingAssetsPath, "Config");
        DirectoryInfo dir = new DirectoryInfo(vbasePath);
        if (!dir.Exists)
            dir.Create(); //创建文件夹

        var vconfigPath = Path.Combine(vbasePath, "ModelInfo.json");
        FileInfo fileInfo = new FileInfo(vconfigPath);
        if (fileInfo.Exists)
            fileInfo.Delete();

        StreamWriter writer = fileInfo.CreateText(); //创建文件
        writer.Write(JsonUtility.ToJson(modelInfoRoot));
        writer.Flush();
        writer.Dispose();
        writer.Close();

        AssetDatabase.Refresh(); //刷新unity工程,只能在编辑器模式下使用
    }
}

/// <summary>
/// 子类
/// 需要序列化
/// </summary>
[Serializable]
public class ModelInfo
{
    
    
    public string Name = null;//属性需要初始化
    public Vector3 localPos = Vector3.zero;
    public Vector3 localRos = Vector3.zero;
    public Vector3 localScale = Vector3.zero;
}

public class ModelInfoRoot
{
    
    
    public List<ModelInfo> ModelInfos = new List<ModelInfo>();//属性需要初始化
}

1.1 generated json data

{
    
    
    "ModelInfos": [
        {
    
    
            "Name": "Cube",
            "localPos": {
    
    
                "x": 0.0,
                "y": 0.0,
                "z": 0.0
            },
            "localRos": {
    
    
                "x": 0.0,
                "y": 0.0,
                "z": 0.0
            },
            "localScale": {
    
    
                "x": 1.0,
                "y": 1.0,
                "z": 1.0
            }
        },
        {
    
    
            "Name": "Cube (1)",
            "localPos": {
    
    
                "x": 100.0,
                "y": 0.0,
                "z": 0.0
            },
            "localRos": {
    
    
                "x": 0.0,
                "y": 0.0,
                "z": 0.0
            },
            "localScale": {
    
    
                "x": 1.0,
                "y": 1.0,
                "z": 1.0
            }
        },
        {
    
    
            "Name": "Cube (2)",
            "localPos": {
    
    
                "x": 0.0,
                "y": 0.0,
                "z": 100.0
            },
            "localRos": {
    
    
                "x": 0.0,
                "y": 0.0,
                "z": 0.0
            },
            "localScale": {
    
    
                "x": 1.0,
                "y": 1.0,
                "z": 1.0
            }
        }
    ]
}

2. Load the json file

using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class LoadJson : MonoBehaviour
{
    
    
    [SerializeField]
    private GameObject cube = null;

    private void Start()
    {
    
    
        StartCoroutine(IELoadJson());
    }

    IEnumerator IELoadJson()
    {
    
    
        var vpath = Path.Combine(Path.Combine(Application.streamingAssetsPath, "Config"), "ModelInfo.json");

        var www = UnityWebRequest.Get(vpath);
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.DataProcessingError || www.result == UnityWebRequest.Result.ProtocolError)
        {
    
    
            Debug.Log(www.error);
        }
        else
        {
    
    
            var vhandler = www.downloadHandler;
            ModelInfoRoot modelInfoRoot = JsonUtility.FromJson<ModelInfoRoot>(vhandler.text);

            if (modelInfoRoot.ModelInfos.Count > 0)
            {
    
    
                foreach (var v in modelInfoRoot.ModelInfos)
                {
    
    
                    var vcube = Instantiate(cube, transform);
                    vcube.name = v.Name;
                    vcube.transform.localPosition = v.localPos;
                    vcube.transform.localEulerAngles = v.localRos;
                    vcube.transform.localScale = v.localScale;
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_39353597/article/details/123354495