Json.net how to serialize object as value

前端 未结 6 1410
滥情空心
滥情空心 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:33

    With the Cinchoo ETL - an open source library to parsing / writing JSON files, you can control the serialization of each object member via ValueConverter or with callback mechanism.

    Method 1:

    The sample below shows how to serialize 'SomeOuterObject' using member level ValueConverters

    public class SomeOuterObject
    {
        public string stringValue { get; set; }
        [ChoTypeConverter(typeof(ToTextConverter))]
        public IPAddress ipValue { get; set; }
    }
    

    And the value converter is

    public class ToTextConverter : IChoValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString();
        }
    }
    

    Finally to serialize the object to file

    using (var jr = new ChoJSONWriter("ipaddr.json")
        )
    {
        var x1 = new SomeOuterObject { stringValue = "X1", ipValue = IPAddress.Parse("12.23.21.23") };
        jr.Write(x1);
    }
    

    And the output is

    [
     {
      "stringValue": "X1",
      "ipValue": "12.23.21.23"
     }
    ]
    

    Method 2:

    This the alternative method to hook up value converter callback to 'ipValue' property. This approach is lean and no need to create value converter for just this operation.

    using (var jr = new ChoJSONWriter("ipaddr.json")
        .WithField("stringValue")
        .WithField("ipValue", valueConverter: (o) => o.ToString())
        )
    {
        var x1 = new SomeOuterObject { stringValue = "X1", ipValue = IPAddress.Parse("12.23.21.23") };
        jr.Write(x1);
    }
    

    Hope this helps.

    Disclaimer: I'm the author of the library.

提交回复
热议问题