Deserialize json with auto-trimming strings

后端 未结 3 1919
我寻月下人不归
我寻月下人不归 2020-12-20 12:20

I use Newtonsoft.Json library

Is there a way to trim spaces from any string data during deserialization?

class Program
{
    class Person
    {
              


        
3条回答
  •  粉色の甜心
    2020-12-20 13:00

    In .net core 3.1 you can use the System.Text.Json to achieve this.

        /// 
        /// Trim spaces
        /// 
        public class TrimmingConverter : JsonConverter
        {
            /// 
            /// Trim the input string
            /// 
            /// reader
            /// Object type
            /// Existing Value
            /// 
            public override string Read(
              ref Utf8JsonReader reader,
              Type typeToConvert,
              JsonSerializerOptions options) => reader.GetString()?.Trim();
    
            /// 
            /// Trim the output string
            /// 
            /// Writer
            /// value
            /// serializer
            public override void Write(
                Utf8JsonWriter writer,
                string dateTimeValue,
                JsonSerializerOptions options) => writer.WriteStringValue(dateTimeValue?.Trim());
        }
    

提交回复
热议问题