标签:
原文:
http://stackoverflow.com/questions/18668617/json-net-error-getting-value-from-scopeid-on-system-net-ipaddress
class IPAddressConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(IPAddress)); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IPAddress ip = (IPAddress)value; writer.WriteValue(ip.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); return IPAddress.Parse(token.Value<string>()); } } class IPEndPointConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(IPEndPoint)); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IPEndPoint ep = (IPEndPoint)value; writer.WriteStartObject(); writer.WritePropertyName("Address"); serializer.Serialize(writer, ep.Address); writer.WritePropertyName("Port"); writer.WriteValue(ep.Port); writer.WriteEndObject(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); IPAddress address = jo["Address"].ToObject<IPAddress>(serializer); int port = jo["Port"].Value<int>(); return new IPEndPoint(address, port); } } public class Program { static void Main(string[] args) { IPEndPoint[] endpoints = new IPEndPoint[] { new IPEndPoint(IPAddress.Parse("8.8.4.4"), 53), new IPEndPoint(IPAddress.Parse("2001:db8::ff00:42:8329"), 81) }; JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new IPEndPointConverter()); settings.Formatting = Formatting.Indented; string json = JsonConvert.SerializeObject(endpoints, settings); Console.WriteLine(json); IPEndPoint[] endpoints2 = JsonConvert.DeserializeObject<IPEndPoint[]>(json, settings); foreach (IPEndPoint ep in endpoints2) { Console.WriteLine(); Console.WriteLine("AddressFamily: " + ep.AddressFamily); Console.WriteLine("Address: " + ep.Address); Console.WriteLine("Port: " + ep.Port); } } }
Json.Net 序列化 IPAddress 或 IPEndPoint
标签:
原文地址:http://www.cnblogs.com/52zmj/p/5463546.html