2
votes

C#
Given:

[JsonObject(MemberSerialization.OptOut)]
public class Customer : DynamicObject{

public string FirstName { get; set; }
public string LastName { get; set; }

}

JavaScript:
var customer = {
FirstName: "John",
LastName: "Doe",
DOB: "12/18/1984"
};

Is there a a setting in JSON.NET or something else that has to happen such that the DOB would be deserialized to strongly typed Customer when json is posted to server?

1
I still haven't solved this.Nathan Carroll

1 Answers

0
votes

to get this to work use custom converter overriding the ReadJson, and WriteJson methods

public class CustomConverter : JsonConverter{

    public override void WriteJson(JsonWriter writer,
                                   object value,
                                   JsonSerializer serializer)
    {
        if (value is DynamicSword)
        {
            var ds = (DynamicSword)value;
            string[] serializable;
            string[] notSerializable;
            ds.SetSerializableAndNotSerializable(out serializable, out notSerializable);                
            var jobject = new JObject();
            foreach (var item in serializable)
            {
                var tempValue = ds[item];
                if (tempValue != null)
                {   
                    jobject.Add(item, JToken.FromObject(tempValue));
                }
            }
            jobject.WriteTo(writer);
        }
        else
        {
            JToken t = JToken.FromObject(value);
            t.WriteTo(writer);
        }
    }


    public override bool CanConvert(Type objectType)
    {
        return true;     
    }

    public override object ReadJson(JsonReader reader,
                                    Type objectType,
                                     object existingValue,
                                     JsonSerializer serializer)
    {
        ConstructorInfo magicConstructor = objectType.GetConstructor(Type.EmptyTypes);
        var newObject = magicConstructor.Invoke(new object[]{});
        JObject jObject = JObject.Load(reader);
        if (newObject is DynamicSword)
        {
            var ds = (DynamicSword)newObject;
            hydrate(jObject, ds);
        }
        else
        {
            //do something different?
            //really shoulnt be in here anyways
        }
        return newObject;
    }

....

}