Json.net how to serialize object as value

前端 未结 6 1446
滥情空心
滥情空心 2020-12-15 19:06

I\'ve pored through the docs, StackOverflow, etc., can\'t seem to find this...

What I want to do is serialize/deserialize a simple value-type of object as a value, n

6条回答
  •  忘掉有多难
    2020-12-15 19:27

    Here is a class for generic conversion of simple value objects that I plan to include in the next update of Activout.RestClient. A "simple value object" as an object that has:

    1. No default constructor
    2. A public property named Value
    3. A constructor taking the same type as the Value property

    var settings = new JsonSerializerSettings
    {
        Converters = new List {new SimpleValueObjectConverter()}
    };
    

    public class SimpleValueObjectConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var valueProperty = GetValueProperty(value.GetType());
            serializer.Serialize(writer, valueProperty.GetValue(value));
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            var valueProperty = GetValueProperty(objectType);
            var value = serializer.Deserialize(reader, valueProperty.PropertyType);
            return Activator.CreateInstance(objectType, value);
        }
    
        public override bool CanConvert(Type objectType)
        {
            if (GetDefaultConstructor(objectType) != null) return false;
            var valueProperty = GetValueProperty(objectType);
            if (valueProperty == null) return false;
            var constructor = GetValueConstructor(objectType, valueProperty);
            return constructor != null;
        }
    
        private static ConstructorInfo GetValueConstructor(Type objectType, PropertyInfo valueProperty)
        {
            return objectType.GetConstructor(new[] {valueProperty.PropertyType});
        }
    
        private static PropertyInfo GetValueProperty(Type objectType)
        {
            return objectType.GetProperty("Value");
        }
    
        private static ConstructorInfo GetDefaultConstructor(Type objectType)
        {
            return objectType.GetConstructor(new Type[0]);
        }
    }
    

提交回复
热议问题