Unity.JsonUtility序列化指南

大致说明


Unity5引入了一套新的Json工具——JsonUtility。
总的来说就是不好用。有大量Json需求的朋友,建议出门左转,使用其他Json库

原本Json相对简单,但是这套工具使用的是Unity Serializer。和我们日常使用的Json序列化有点差异。支持序列化MonoBehaviour的子类,ScriptableObject的子类以及包含[Serializable]标签的类和结构。
这套Api主要优势是Unity内置,在很多简单的场景,可以方便我们开发。

基本用法


不做介绍,点击查看官方文档

默认为utf-8格式,不支持utf-8带bom
如果序列化的时候遇到莫名其妙的JSON parse error: Invalid value,可以先检查一下是否使用了带bom的格式。

序列化ScriptableObject和MonoBehavior


public class JsonTest : MonoBehaviour
{
    /// <summary>
    /// 序列化字段
    /// </summary>
    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<JsonTest>(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> Item1;
    // 有标签可以正常序列化
    public List<Item2> Item2;
}

public void Run()
{
    var collection = new ListCollection()
    {
        Item0 = new List<int>() { 0, 1, 2, 3, 4 },
        Item1 = new List<Item1>() { new Item1() { Str = "1" }, new Item1() { Str = "2" } },
        Item2 = new List<Item2>() { 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.FromJson<List<int>>("[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<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>> (newJson);
        return wrapper.array;
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] array;
    }
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Unity使用Google.Protobuf.dll进行序列化和反序列化,你需要按照以下步骤进行操作: 1. 下载并安装Google.Protobuf.dll。 2. 在Unity创建一个新的C#脚本,并将其命名为“ProtoHelper”(或任何你想要的名称)。 3. 在脚本添加以下代码: ```csharp using Google.Protobuf; using System.IO; public static class ProtoHelper { public static byte[] Serialize<T>(T obj) where T : IMessage<T> { using (MemoryStream stream = new MemoryStream()) { obj.WriteTo(stream); return stream.ToArray(); } } public static T Deserialize<T>(byte[] bytes) where T : IMessage<T>, new() { T message = new T(); message.MergeFrom(bytes); return message; } } ``` 这个代码片段创建了一个名为“ProtoHelper”的静态类,并包含两个静态方法:SerializeDeserialize。 Serialize方法将一个IMessage<T>对象序列化为一个字节数组,而Deserialize方法将一个字节数组反序列化为一个IMessage<T>对象。 4. 现在你可以在任何其他C#脚本使用这些方法来序列化和反序列化你的ProtoBuf消息。例如: ```csharp using Google.Protobuf; using UnityEngine; public class MyClass : MonoBehaviour { private void Start() { // 创建一个新的ProtoBuf消息 MyMessage message = new MyMessage { Id = 123, Name = "John Doe" }; // 序列化消息 byte[] bytes = ProtoHelper.Serialize(message); // 反序列化消息 MyMessage deserializedMessage = ProtoHelper.Deserialize<MyMessage>(bytes); // 输出消息 Debug.Log(deserializedMessage); } } ``` 这个示例创建了一个名为“MyClass”的MonoBehaviour,并在Start方法创建了一个新的MyMessage对象。然后,它使用ProtoHelper.Serialize方法将该消息序列化为一个字节数组,并使用ProtoHelper.Deserialize方法将该字节数组反序列化为一个新的MyMessage对象。最后,它将反序列化的消息输出到Unity的控制台窗口。 这就是使用Google.Protobuf.dll在Unity进行序列化和反序列化的基本步骤。记住,你需要正确安装Google.Protobuf.dll,以便在Unity使用它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值