Skip to content

ReadJson does not respect types when dealing with anonymous types #1

@PaulDevenney

Description

@PaulDevenney

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 = "bob@bob.com",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;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions