andras
andras

Reputation: 3645

Json.NET vs Newtonsoft.Json SerializationBinder is different

I know there are many similar questions in this topic, yet I did not find my answer here.

I have downloaded Json.net in Unity and Newtonsoft.json as a NuGet package in a different project. The Newtonsoft.json is working and I tried to use this working solution in a Unity project.

I need to use ISerializationBinder for converting an abstract class hierarchy and I want to serialize/deserialize the classnames only, and not their full assembly name. (Reason for that is that the C# code should communicate with a different program.)

I use a solution that has the following class for serializing (copied from an official example online):

public class KnownTypesBinder : ISerializationBinder
{
    public IList<Type> KnownTypes { get; set; }

    public Type BindToType(string assemblyName, string typeName)
    {
        return KnownTypes.SingleOrDefault(t => t.Name == typeName);
    }

    public void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        assemblyName = null;
        typeName = serializedType.Name;
    }
}

ISerializationBinder does not exist in Json.net. The JsonSerializerSettings is clearly different:

Newtonsoft.json:

public class JsonSerializerSettings 
{
    public ISerializationBinder SerializationBinder { get; set; }
}

Json.net:

public class JsonSerializerSettings
{
    public SerializationBinder Binder { get; set; }
}

System.Runtime.Serialization.SerializationBinder (is not derived from ISerializationBinder) has no method called public void BindToName(Type serializedType, out string assemblyName, out string typeName), which means the type name cannot be defined.

Thanks.

Upvotes: 2

Views: 5545

Answers (1)

Applejag
Applejag

Reputation: 1248

This is a versioning issue. The JSON .NET for Unity you are referring to as just Json.NET uses (as mentioned in the comments) Newtonsoft.Json 8.0.3.

If you want to use fresh features from Newtonsoft.Json I suggest jumping to a different solution. The currently most up-to-date fork of Newtonsoft.Json made for Unity is here: https://github.com/jilleJr/Newtonsoft.Json-for-Unity#readme, being at Newtonsoft.Json 12.0.3 at the time of writing.

jilleJr/Newtonsoft.Json-for-Unity is also deployed via the builtin Unity Package Manager, so staying up-to-date will be easier as a user as well.

Upvotes: 1

Related Questions