using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Newtonsoft.Json
{
///
/// Converts an from and to JSON.
///
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class IPAddressConverter : JsonConverter
{
///
/// List of known types to use this converver.
///
public static readonly Type[] KnownTypes =
[
typeof(IPAddress),
typeof(IPAddress[]),
typeof(List),
typeof(IEnumerable)
];
///
public override bool CanConvert(Type objectType)
=> KnownTypes.Contains(objectType);
///
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return null;
string str = (string)reader.Value;
if (typeof(IPAddress) == objectType)
return IPAddress.Parse(str);
var ips = str.Split(';').Select(s => IPAddress.Parse(s));
if (typeof(IPAddress[]) == objectType)
return ips.ToArray();
if (typeof(List) == objectType)
return ips.ToList();
return ips;
}
///
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string str = null;
if (value == null)
{
writer.WriteValue(str);
return;
}
if (value is IPAddress addr)
str = addr.ToString();
if (value is IPAddress[] addrArray)
str = string.Join(";", addrArray.Select(ip => ip.ToString()));
if (value is List addrList)
str = string.Join(";", addrList.Select(ip => ip.ToString()));
if (value is IEnumerable addrEnum)
str = string.Join(";", addrEnum.Select(ip => ip.ToString()));
writer.WriteValue(str);
}
}
}