Alternate property name while deserializing

前端 未结 2 1335
野趣味
野趣味 2020-11-27 06:36

In reference to this question:

How can I change property names when serializing with Json.net?

Sure, great, but can I have the cake and eat it?

What

2条回答
  •  庸人自扰
    2020-11-27 06:50

    Another way of accomplishing this is intercepting the serialization/deserialization process early, by doing some overrides the JsonReader and JsonWriter

    public class CustomJsonWriter : JsonTextWriter
    {
        private readonly Dictionary _backwardMappings;
    
        public CustomJsonWriter(TextWriter writer, Dictionary backwardMappings)
            : base(writer)
        {
            _backwardMappings = backwardMappings;
        }
    
        public override void WritePropertyName(string name)
        {
            base.WritePropertyName(_backwardMappings[name]);
        }
    }
    
    public class CustomJsonReader : JsonTextReader
    {
        private readonly Dictionary _forwardMappings;
    
    
        public CustomJsonReader(TextReader reader, Dictionary forwardMappings )
            : base(reader)
        {
            _forwardMappings = forwardMappings;
        }
    
        public override object Value
        {
            get
            {
                if (TokenType != JsonToken.PropertyName)
                    return base.Value;
    
                return _forwardMappings[base.Value.ToString()];
            }
        }
    }
    

    After doing this, you can serialize by doing

    var mappings = new Dictionary
    {
        {"Property1", "Equivalent1"},
        {"Property2", "Equivalent2"},
    };
    var builder = new StringBuilder();
    JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder), mappings), your_object);
    

    and deserialize by doing

    var mappings = new Dictionary
    {
        {"Equivalent1", "Property1"},
        {"Equivalent2", "Property2"},
    };
    var txtReader = new CustomJsonReader(new StringReader(jsonString), mappings);
    var your_object = JsonSerializer.Create().Deserialize(txtReader);
    

提交回复
热议问题