JSON.NET强类型对象继承自DynamicObject反序列化/序列化

时间:2013-12-18 13:30:02

标签: dynamic json.net deserialization

C#
下式给出:

[JSONObject的(MemberSerialization.OptOut)]
公共类客户:DynamicObject {

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

}

的JavaScript:
var customer = {
名字:“约翰”,
姓氏:“Doe”,
DOB:“12/18/1984”
};

JSON.NET中是否有设置或其他必须发生的设置,以便在json发布到服务器时将DOB反序列化为强类型客户?

1 个答案:

答案 0 :(得分:0)

要使其工作,请使用自定义转换器覆盖ReadJson和WriteJson方法

公共类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;
    }

...

}