问题
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.
- So, how can I solve the serialization - by using only the class names - in Unity? (Only setting
TypeNameHandling = TypeNameHandling.Objects,
is no solution here) - Why does everyone claim that they are the same when it is clearly not the case? (Even the StackOverflow tag below for
Json.net
does that.) - Does the difference have anything to do with the fact that Unity uses Mono?
Thanks.
回答1:
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.
来源:https://stackoverflow.com/questions/52307935/json-net-vs-newtonsoft-json-serializationbinder-is-different