101 lines
2.4 KiB
C#
101 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
#if NET8_0_OR_GREATER
|
|
using IPNetwork = System.Net.IPNetwork;
|
|
#else
|
|
using Microsoft.AspNetCore.HttpOverrides;
|
|
using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork;
|
|
#endif
|
|
|
|
namespace Newtonsoft.Json
|
|
{
|
|
/// <summary>
|
|
/// Converts an <see cref="IPNetwork"/> from and to JSON.
|
|
/// </summary>
|
|
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
|
public class IpNetworkConverter : JsonConverter
|
|
{
|
|
/// <summary>
|
|
/// List of known types to use this converver.
|
|
/// </summary>
|
|
public static readonly Type[] KnownTypes =
|
|
[
|
|
typeof(IPNetwork),
|
|
typeof(IPNetwork[]),
|
|
typeof(List<IPNetwork>),
|
|
typeof(IEnumerable<IPNetwork>)
|
|
];
|
|
|
|
/// <inheritdoc/>
|
|
public override bool CanConvert(Type objectType)
|
|
=> 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(IPNetwork) == objectType)
|
|
return Parse(str);
|
|
|
|
var networks = str.Split(';').Select(Parse);
|
|
|
|
if (typeof(IPNetwork[]) == objectType)
|
|
return networks.ToArray();
|
|
|
|
if (typeof(List<IPNetwork>) == objectType)
|
|
return networks.ToList();
|
|
|
|
return networks;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
{
|
|
string str = null;
|
|
if (value == null)
|
|
{
|
|
writer.WriteValue(str);
|
|
return;
|
|
}
|
|
|
|
if (value is IPNetwork net)
|
|
str = ToString(net);
|
|
|
|
if (value is IPNetwork[] netArray)
|
|
str = string.Join(";", netArray.Select(ToString));
|
|
|
|
if (value is List<IPNetwork> netList)
|
|
str = string.Join(";", netList.Select(ToString));
|
|
|
|
if (value is IEnumerable<IPNetwork> netEnum)
|
|
str = string.Join(";", netEnum.Select(ToString));
|
|
|
|
writer.WriteValue(str);
|
|
}
|
|
|
|
private static string ToString(IPNetwork net)
|
|
{
|
|
#if NET8_0_OR_GREATER
|
|
return $"{net.BaseAddress}/{net.PrefixLength}";
|
|
#else
|
|
return $"{net.Prefix}/{net.PrefixLength}";
|
|
#endif
|
|
}
|
|
|
|
private static IPNetwork Parse(string str)
|
|
{
|
|
string[] parts = str.Split('/');
|
|
var prefix = IPAddress.Parse(parts.First());
|
|
int prefixLength = int.Parse(parts.Last());
|
|
|
|
return new IPNetwork(prefix, prefixLength);
|
|
}
|
|
}
|
|
}
|