2

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. Commented Jun 2, 2014 at 16:54

1 Answer 1

0

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;
    }

....

}

Sign up to request clarification or add additional context in comments.

2 Comments

This is not anywhere near complete but it shows can be done with JSON.NET without too much trouble.
[JsonConverter(typeof(CustomConverter))] public class TestClass1 : DynamicSword have to put attribute for JsonConverter on the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.