JsonUtility

作者:追风剑情 发布于:2017-4-19 13:26 分类:Unity3d

Unity原生Json工具类

示例一:测试序列化与反序列化


using UnityEngine;
public class Test : MonoBehaviour {

	void Start () {
            TestJsonObject obj = new TestJsonObject();
            obj.test_uint = 10;
            obj.test_int = 20;
            obj.test_float = 30.5f;
            obj.test_double = 40.6;
            obj.test_string = "test!中文";
            obj.test_ignore = "ignore_field";

            string json = JsonUtility.ToJson(obj);
            Debug.Log(json);

            TestJsonObject obj1 = JsonUtility.FromJson<TestJsonObject>(json);
            Debug.Log(obj1.ToString());
	}
}

[System.Serializable]
public class TestJsonObject
{
    public uint test_uint;
    public int test_int;
    public float test_float;
    public double test_double;
    public string test_string;
    [System.NonSerialized]
    public string test_ignore;

    private static TestJsonObject mInstance;
    public static TestJsonObject Instance
    {
        get
        {
            if (null == mInstance)
                mInstance = new TestJsonObject();
            return mInstance;
        }
    }

    public override string ToString()
    {
        return string.Format(
            "<Serializable:{0}, test_int:{1}, test_float:{2}, test_double={3}, test_string={4}>",
            test_uint, test_int, test_float, test_double, test_string);
    }
}


运行测试

11111.png


using System;
using UnityEngine;

[Serializable]
public class TestSerialize : ISerializationCallbackReceiver
{
    // 序列化之后调用
    public void OnAfterDeserialize()
    {
    }

    // 序列化之前调用
    public void OnBeforeSerialize()
    {
    }
}


标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号