expression-json-serializer icon indicating copy to clipboard operation
expression-json-serializer copied to clipboard

ReadJson does not respect types when dealing with anonymous types

Open PaulDevenney opened this issue 11 years ago • 1 comments

The following example fails to convert successfully as during deserialization it creates the Expression as Expression<Func<Profile, Anonymous[string, string]>> rather than Expression<Func<Profile, object>>, even though that is the object type passed into the converter.ReadJson method

    static void Main(string[] args)
    {
        var profile = new Profile()
        {
            Email = "[email protected]",SiteCode = "www.testweb.com",FirstName = "bob"
        };

        var settings = new JsonSerializerSettings() {TypeNameHandling = TypeNameHandling.Objects};
        settings.Converters.Add(new ExpressionConverter<Expression<Func<Profile, object>>>());

        var indexDefinition2 = new FoundocIndex<Profile>()
        {
            IndexType = IndexType.ImmediatelyConsistent,
            IsUniqueConstraint = true,
            Name = "ByEmail",
            Map = (p => new { profile.SiteCode, profile.Email })
        };

        var test2 = JsonConvert.SerializeObject(indexDefinition2, settings);
        var indexDefinition3 = JsonConvert.DeserializeObject<FoundocIndex<Profile>>(test2, settings);//<--fails
    }


public class ExpressionConverter<T> : JsonConverter where T:class
{
    public override bool CanConvert(Type objectType)
    {
        bool canConvert = objectType == typeof (T);
        return canConvert;
    }
    public override bool CanRead
    {
        get
        {
            return true;
        }
    }
    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var expression = (Expression)value;
        var converter = new Aq.ExpressionJsonSerializer.ExpressionJsonConverter(this.GetType().Assembly);
        converter.WriteJson(writer, expression, new JsonSerializer());
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var converter = new Aq.ExpressionJsonSerializer.ExpressionJsonConverter(this.GetType().Assembly);
        var result = converter.ReadJson(reader, objectType, existingValue, serializer);


        return result;
    }
}

PaulDevenney avatar Sep 11 '14 13:09 PaulDevenney

I'm sorry, but I don't have time to support this library atm, plus it's not relevant to my current field of work, unfortunately, so it is unlikely I will review the code any time soon. You are welcome to fork and patch, though, I'm glad someone tried and used it.

aquilae avatar Sep 25 '14 13:09 aquilae