提问者:小点点

JSON.NET 从动态对象反序列化/序列化继承的强类型对象


C#
给定:

[JsonObject(MemberSerialization.OptOut)]
公共类 客户 : 动态对象{

公共字符串 FirstName { get; set; }
公共字符串 LastName { get; set; }



}

JavaScript:
var customer = { FirstName: “John”,

LastName: “Doe”,
DOB: “12/18/1984”
};

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


共1个答案

匿名用户

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

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

....

}