簡體   English   中英

在反序列化數組中的項時忽略自定義JsonConverter

[英]Custom JsonConverter ignored when deserializing item in array

編輯:制作一個更簡單,更透明的樣本案例

我正在嘗試反序列化一組組件(屬於一個實體)。 其中一個組件是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組件。 我猜測Deserializing to Component []會讓串行器只使用故障轉換器嗎? 我有什么想法可能做錯了嗎?

編輯我剛剛嘗試了一個非通用的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的來源,但是我正在努力讓它運行起來。

我看了一下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);
                            }

它不會檢查每個單獨的數組項的類型以查找相應的轉換器。

因此,我需要找到與使用轉換器不同的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM