Added Converters/Formatters for Serialization of Json/MessagePack
This commit is contained in:
78
AMWD.Common/Converters/IPAddressConverter.cs
Normal file
78
AMWD.Common/Converters/IPAddressConverter.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
|
||||
namespace Newtonsoft.Json
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts an <see cref="IPAddress"/> from and to JSON.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class IPAddressConverter : JsonConverter
|
||||
{
|
||||
/// <summary>
|
||||
/// List of known types to use this converver.
|
||||
/// </summary>
|
||||
public static readonly Type[] KnownTypes = new[]
|
||||
{
|
||||
typeof(IPAddress),
|
||||
typeof(IPAddress[]),
|
||||
typeof(List<IPAddress>),
|
||||
typeof(IEnumerable<IPAddress>)
|
||||
};
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return KnownTypes.Contains(objectType);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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<IPAddress>) == objectType)
|
||||
return ips.ToList();
|
||||
|
||||
return ips;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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<IPAddress> addrList)
|
||||
str = string.Join(";", addrList.Select(ip => ip.ToString()));
|
||||
|
||||
if (value is List<IPAddress> addrEnum)
|
||||
str = string.Join(";", addrEnum.Select(ip => ip.ToString()));
|
||||
|
||||
writer.WriteValue(str);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user