Json.net how to serialize object as value

前端 未结 6 1428
滥情空心
滥情空心 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条回答
  •  萌比男神i
    2020-12-15 19:25

    You can handle this using a custom JsonConverter for the IPAddress class. Here is the code you would need:

    public class IPAddressConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(IPAddress));
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return new IPAddress(JToken.Load(reader).ToString());
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JToken.FromObject(value.ToString()).WriteTo(writer);
        }
    }
    

    Then, add a [JsonConverter] attribute to your IPAddress class and you're ready to go:

    [JsonConverter(typeof(IPAddressConverter))]
    public class IPAddress
    {
        byte[] bytes;
    
        public IPAddress(string address)
        {
            bytes = address.Split('.').Select(s => byte.Parse(s)).ToArray();
        }
    
        public override string ToString() 
        { 
            return string.Join(".", bytes.Select(b => b.ToString()).ToArray()); 
        }
    }
    

    Here is a working demo:

    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = new IPAddress("192.168.1.2");
            var obj = new SomeOuterObject() { stringValue = "Some String", ipValue = ip };
            string json = JsonConvert.SerializeObject(obj);
            Console.WriteLine(json);
        }
    }
    
    public class SomeOuterObject
    {
        public string stringValue { get; set; }
        public IPAddress ipValue { get; set; }
    }
    

    Output:

    {"stringValue":"Some String","ipValue":"192.168.1.2"}
    

提交回复
热议问题