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;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
photonnetwork.instantiate에서 gamepobject 유형을 생성 한 다음 상태 및 값을 참조하는 방법주로 마지막 기사에서 일어난 일의 수정입니다. 지난번↓ 그럼 주제입니다. (타이틀이 정리되어 없어서 죄송합니다) 우선 전회의 Illegal view ID:0입니다만 photonnetwork.instantiate를 사...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.