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 { /// /// Converts an from and to JSON. /// [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public class IpNetworkConverter : JsonConverter { /// /// List of known types to use this converver. /// public static readonly Type[] KnownTypes = [ typeof(IPNetwork), typeof(IPNetwork[]), 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(IPNetwork) == objectType) return Parse(str); var networks = str.Split(';').Select(Parse); if (typeof(IPNetwork[]) == objectType) return networks.ToArray(); if (typeof(List) == objectType) return networks.ToList(); return networks; } /// 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 netList) str = string.Join(";", netList.Select(ToString)); if (value is IEnumerable 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); } } }