deniszykov / msgpack-unity3d

MessagePack and JSON serializer for Unity3D
MIT License
102 stars 14 forks source link
json json-serialization messagepack messagepack-serializer unity-asset unity-plugin unity3d

Build Status

Introduction

This package provides an API for data serialization/deserialization into MessagePack and JSON formats.

Supported Platforms:

API

Installation

NuGet

PM> Install-Package GameDevWare.Serialization

Unity3D

Json + MessagePack Serializer

Example

Serialize an object into a Stream using a MessagePack serializer:

var outputStream = new MemoryStream();
MsgPack.Serialize(new { field1 = 1, field2 = 2 }, outputStream);
outputStream.Position = 0; // rewind stream before copying/reading

Deserialize an object from a Stream using a MessagePack serializer:

Stream inputStream;
MsgPack.Deserialize(typeof(MyObject), inputStream); // -> instance of MyObject
// or
MsgPack.Deserialize<MyObject>(inputStream); // -> instance of MyObject

Breaking Change in v2.0

Message Pack Endianness

Message Pack serialization prior to v2.0 used a little-endian byte order for multi-byte integers. That doesn't correspond to the specification. Data saved with little-endian formatting could be re-written to big-endian with the following code:

var context = new SerializationContext { Options = SerializationOptions.SuppressTypeInformation };
using (var fileStream = File.Open("<path to file>", FileMode.Open, FileAccess.ReadWrite))
{
    var reader = new MsgPackReader(fileStream, context, Endianness.LittleEndian);
    var value = reader.ReadValue(typeof(object));
    fileStream.Position = 0;
    var writer = new MsgPackWriter(fileStream, context);
    writer.WriteValue(value, typeof(object));
    fileStream.SetLength(fileStream.Position);
}

Data Contract Attributes

Mapping Types

The MessagePack/Json serializer is guided by Data Contract rules. Its behavior can be changed with DataContract, DataMember, and IgnoreDataMember attributes. Attributes can be from System.Runtime.Serialization.dll or your attributes with the same names.

Supported Types

Custom Type Serializers

To implement a custom TypeSerializer you need to inherit from TypeSerializer and override the Deserialize and Serialize methods.

public sealed class GuidSerializer : TypeSerializer
{
    public override Type SerializedType { get { return typeof(Guid); } }

    public override object Deserialize(IJsonReader reader)
    { 
        // General rule of 'Deserialize' is to leave reader on
        // last token of deserialized value. It is EndOfObject or EndOfArray, or Value.
        // 'nextToken: true' will call 'reader.NextToken()' AFTER 'ReadString()'.
        // Since it is last token on de-serialized value we set 'nextToken: false'.
        var guidStr = reader.ReadString(nextToken: false);
        var value = new Guid(guidStr);
        return value;
    }

    public override void Serialize(IJsonWriter writer, object valueObj)
    {
        var value = (Guid)valueObj; // valueObj is not null
        var guidStr = value.ToString();
        writer.Write(guidStr);
    }
}

Then you need to register your class in the Json.DefaultSerializers collection or mark it with the TypeSerializerAttribute.

Extra Type Information

There is additional type information with each serialized object. It increases the size of the serialized data. If you do not want to store object's type information, specify SuppressTypeInformation when calling the Serialize method.

MsgPack.Serialize(value, stream, SerializationOptions.SuppressTypeInformation);

If you want to ignore type information when deserializing an object, specify SuppressTypeInformation when calling the Deserialize method.

MsgPack.Deserialize(typeof(MyObject), stream, SerializationOptions.SuppressTypeInformation);

IL2CPP - AOT :grey_exclamation:

Additional preparation should be made for AOT execution platforms. A link.xml file should be added to the project's root folder. This file should exclude the System.Runtime.Serialization.dll assembly from IL stripping. Read more about IL code stripping in the official documentation.

Contacts

Please send any questions at support@gamedevware.com

License

MIT