编辑:创建了一个更简单,更透明的示例案例
我正在尝试反序列化一系列组件(属于一个实体)。 组件之一是Sprite组件,其中包含纹理和动画信息。我已经为此实现了一个CustomConverter,因为原始的sprite类有点肿,并且也没有无参数的构造函数(该类来自单独的库,因此我无法对其进行修改)。
实际用例要复杂一些,但是我在下面添加了一个类似的示例。我测试了代码,并出现了相同的问题。反序列化时从不使用ReadJson。但是当序列化WriteJson时,它的调用就可以了。
这些是它的组件和自定义转换器;
public class ComponentSample
{
int entityID;
}
public class Rect
{
public int x;
public int y;
public int width;
public int height;
public Rect( int x, int y, int width, int height )
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
//this class would normally have a texture and a bunch of other data that is hard to serialize
//so we will use a jsonconverter to instead point to an atlas that contains the texture's path and misc data
public class SpriteSample<TEnum> : ComponentSample
{
Dictionary<TEnum, Rect[]> animations = new Dictionary<TEnum, Rect[]>();
public SpriteSample( TEnum animationKey, Rect[] frames )
{
this.animations.Add( animationKey, frames );
}
}
public class SpriteSampleConverter : JsonConverter<SpriteSample<int>>
{
public override SpriteSample<int> ReadJson( JsonReader reader, Type objectType, SpriteSample<int> existingValue, bool hasExistingValue, JsonSerializer serializer )
{
JObject jsonObj = JObject.Load( reader );
//get texturepacker atlas
string atlasPath = jsonObj.Value<String>( "atlasPath" );
//some wizardy to get all the animation and load the texture and stuff
//for simplicity sake I'll just put in some random data
return new SpriteSample<int>( 99, new Rect[ 1 ] { new Rect( 0, 0, 16, 16 ) } );
}
public override void WriteJson( JsonWriter writer, SpriteSample<int> value, JsonSerializer serializer )
{
writer.WriteStartObject();
writer.WritePropertyName( "$type" );
//actually don't know how to get the type, so I just serialized the SpriteSample<int> to check
writer.WriteValue( "JsonSample.SpriteSample`1[[System.Int32, mscorlib]], NezHoorn" );
writer.WritePropertyName( "animationAtlas" );
writer.WriteValue( "sampleAtlasPathGoesHere" );
writer.WriteEndObject();
}
}
在序列化时它会正确生成Json;
JsonSerializer serializer = new JsonSerializer();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
settings.PreserveReferencesHandling = PreserveReferencesHandling.All; //none
settings.TypeNameHandling = TypeNameHandling.All;
settings.Formatting = Formatting.Indented;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
settings.Converters.Add( new SpriteSampleConverter() );
ComponentSample[] components = new ComponentSample[]
{
new ComponentSample(),
new ComponentSample(),
new SpriteSample<int>(10, new Rect[] { new Rect(0,0,32,32 ) } )
};
string fullFile = "sample.json";
string directoryPath = Path.GetDirectoryName( fullFile );
if ( directoryPath != "" )
Directory.CreateDirectory( directoryPath );
using ( StreamWriter file = File.CreateText( fullFile ) )
{
string jsonString = JsonConvert.SerializeObject( components, settings );
file.Write( jsonString );
}
Json:
{
"$id": "1",
"$type": "JsonSample.ComponentSample[], NezHoorn",
"$values": [
{
"$id": "2",
"$type": "JsonSample.ComponentSample, NezHoorn"
},
{
"$id": "3",
"$type": "JsonSample.ComponentSample, NezHoorn"
},
{
"$type": "JsonSample.SpriteSample`1[[System.Int32, mscorlib]], NezHoorn",
"animationAtlas": "sampleAtlasPathGoesHere"
}
]
}
但是当我尝试反序列化列表时,它从不调用SpriteSampleConverter上的ReadJson,而只是尝试按原样反序列化对象。
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
settings.TypeNameHandling = TypeNameHandling.All;
settings.Formatting = Formatting.Indented;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
settings.Converters.Add( new SpriteSampleConverter() );
using ( StreamReader file = File.OpenText( "sample.json" ) )
{
//JsonConvert.PopulateObject( file.ReadToEnd(), man, settings );
JObject componentsJson = JObject.Parse( file.ReadToEnd() );
//ComponentList components = JsonConvert.DeserializeObject<ComponentList>( componentsJson.ToString(), settings );
JArray array = JArray.Parse( componentsJson.GetValue( "$values" ).ToString() );
ComponentSample[] list = JsonConvert.DeserializeObject<ComponentSample[]>( array.ToString(), settings );
//The SpriteSampleConverter does work here!
SpriteSample<int> deserializedSprite = JsonConvert.DeserializeObject<SpriteSample<int>>( componentsJson.GetValue( "$values" ).ElementAt(2).ToString(), settings );
}
我做了一个快速测试,看SpriteSampleConverter是否起作用,ReadJson确实在这里被调用;
SpriteSample deserializedSprite = JsonConvert.DeserializeObject>(componentsJson.GetValue(“ $ values”).ElementAt(2).ToString(),settings);
这不是有效的解决方案,因为我不知道对象是否/在何处具有Sprite组件。 我猜想反序列化为Component []会使序列化程序仅使用defeault转换器? 有什么想法我可能做错了吗?
修改 我刚刚尝试了一个非通用的JsonConverter来查看是否调用了CanConvert,并且令人惊讶的是,在检查ComponentSample []和ComponentSample类型时调用了它,但SpriteSample从未通过检查。
public class SpriteSampleConverterTwo : JsonConverter
{
public override bool CanConvert( Type objectType )
{
return objectType == typeof( SpriteSample<int> );
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
{
JObject jsonObj = JObject.Load( reader );
//get texturepacker atlas
string atlasPath = jsonObj.Value<String>( "atlasPath" );
//some wizardy to get all the animation and load the texture and stuff
//for simplicity sake I'll just put in some random data
return new SpriteSample<int>( 99, new Rect[ 1 ] { new Rect( 0, 0, 16, 16 ) } );
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
{
writer.WriteStartObject();
writer.WritePropertyName( "$type" );
//actually don't know how to get the type, so I just serialized the SpriteSample<int> to check
writer.WriteValue( "JsonSample.SpriteSample`1[[System.Int32, mscorlib]], NezHoorn" );
writer.WritePropertyName( "animationAtlas" );
writer.WriteValue( "sampleAtlasPathGoesHere" );
writer.WriteEndObject();
}
}
我希望我可以看一下json.net的来源,但是我遇到了很多麻烦 让它运行。
答案 0 :(得分:1)
我看了一下json.net源代码,得出的结论是,只有数组的声明类型将用于检查转换器;
JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty);
int? previousErrorIndex = null;
bool finished = false;
do
{
try
{
if (reader.ReadForType(contract.ItemContract, collectionItemConverter != null))
{
switch (reader.TokenType)
{
case JsonToken.EndArray:
finished = true;
break;
case JsonToken.Comment:
break;
default:
object value;
if (collectionItemConverter != null && collectionItemConverter.CanRead)
{
value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null);
}
它不会检查每个单独的数组项的类型以寻找相应的转换器。
所以我将需要找到与使用转换器不同的解决方案。