Unity.JsonUtility 시리얼화 가이드

6251 단어 Unity
대강 설명하다
Unity5는 새로운 Json 도구인 Json Utility를 도입했다.전반적으로 말하면 쓰기 힘들다.Json이 많이 필요하신 분들은 밖에 나가서 좌회전해서 다른 Json 라이브러리를 사용하세요.
원래 Json은 비교적 간단하지만 이 도구는 Unity Serializer를 사용한다.우리가 일상적으로 사용하는 제이슨 서열화와는 조금 차이가 있다.MonoBehaviour의 하위 클래스, ScriptableObject의 하위 클래스, [serializable] 태그가 포함된 클래스와 구조를 서열화할 수 있습니다.이 Api의 주요 장점은 Unity가 내장되어 있고 많은 간단한 장면에서 우리가 개발하는 데 편리하다는 것이다.
기본용법
소개 안 하고 클릭하여 공식 문서 보기
기본값은 utf-8 형식으로, 지원되지 않습니다utf-8 bom.만약 서열화할 때 영문도 모른 경우JSON parse error: Invalid value를 만나면bom이 있는 포맷을 사용했는지 확인해 볼 수 있다.
Scriptable Object 및 MonoBehavior 시리얼화
public class JsonTest : MonoBehaviour
{
    /// 
    ///      
    /// 
    public int Value;

    void Start()
    {
        //   Value 2
        Value = 1;

        // {"Value":1}
        var json = JsonUtility.ToJson(this);

        //   Value 2
        Value = 2;

        //        ,Value   1
        JsonUtility.FromJsonOverwrite(json, this);

        // ArgumentException: Cannot deserialize JSON to new instances of type 'JsonTest.'
        //              MonoBehavior   
        var fromJson = JsonUtility.FromJson(json);
    }
}

序列化List和Dictionary和Array


如果要支持List和Array,建议写一个包装类,将其包含再里边。并且泛型中加入[Serializable]标签
如果要支持Dictionary,建议改写成List。

//     [Serializable]  ,           
public class Item1
{
    public string Str;
}

//            
[Serializable]
public class Item2
{
    public string Str;
}

public class ListCollection
{
    //       
    public List<int> Item0;
    //            
    public List Item1;
    //           
    public List Item2;
}

public void Run()
{
    var collection = new ListCollection()
    {
        Item0 = new List<int>() { 0, 1, 2, 3, 4 },
        Item1 = new List() { new Item1() { Str = "1" }, new Item1() { Str = "2" } },
        Item2 = new List() { new Item2() { Str = "1" }, new Item2() { Str = "2" } }
    };

    // {"Item0":[0,1,2,3,4],"Item2":[{"Str":"1"},{"Str":"2"}]}
    Debug.Log(JsonUtility.ToJson(collection));
    // {}
    Debug.Log(JsonUtility.ToJson(collection.Item0));
    // {}
    Debug.Log(JsonUtility.ToJson(collection.Item1));
    // {}
    Debug.Log(JsonUtility.ToJson(collection.Item2));

    // ArgumentException: JSON must represent an object type.
    var fromJson = JsonUtility.FromJsonint>>("[0,1,2,3,4]");
    Debug.Log(fromJson.Count);
}

여기에 비뚤어진 과일 알맹이가 쓴 빠른 포장 방법을 제공한다.필요한 친구는 사용을 고려해 볼 수 있다.
//   
// https://forum.unity3d.com/threads/how-to-load-an-array-with-jsonutility.375735/#post-2585129
public class JsonHelper
{
    public static T[] getJsonArray(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper wrapper = JsonUtility.FromJson> (newJson);
        return wrapper.array;
    }

    [Serializable]
    private class Wrapper
    {
        public T[] array;
    }
}

좋은 웹페이지 즐겨찾기