public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Dictionary<string, object> routeHashValue = serializer.Deserialize<Dictionary<string, object>>(reader); if (routeHashValue == null) return null; Route route = new Route(); route.Id = routeHashValue.ContainsKey("id") && routeHashValue["id"] != null ? JsonConvert.DeserializeObject<int>(routeHashValue["id"].ToString()) : 0; route.Parts = routeHashValue.ContainsKey("parts") && routeHashValue["parts"] != null ? JsonConvert.DeserializeObject<int[]>(routeHashValue["parts"].ToString()) : null; route.Points = routeHashValue.ContainsKey("points") && routeHashValue["points"] != null ? JsonConvert.DeserializeObject<PointWithMeasure[]>(routeHashValue["points"].ToString()) : null; route.Style = routeHashValue.ContainsKey("style") && routeHashValue["style"] != null ? JsonConvert.DeserializeObject<Style>(routeHashValue["style"].ToString()) : null; route.Type = GeometryType.UNKNOWN; GeometryType geoType = GeometryType.UNKNOWN; if (routeHashValue.ContainsKey("type") && routeHashValue["type"] != null) { geoType = (GeometryType)Enum.Parse(typeof(GeometryType), routeHashValue["type"].ToString(), false); route.Type = geoType; } route.Length = routeHashValue.ContainsKey("length") && routeHashValue["length"] != null ? JsonConvert.DeserializeObject<double>(routeHashValue["length"].ToString()) : 0.0; route.MaxM = routeHashValue.ContainsKey("maxM") && routeHashValue["maxM"] != null ? JsonConvert.DeserializeObject<int>(routeHashValue["maxM"].ToString()) : 0; route.MinM = routeHashValue.ContainsKey("minM") && routeHashValue["minM"] != null ? JsonConvert.DeserializeObject<int>(routeHashValue["minM"].ToString()) : 0; route.Line = routeHashValue.ContainsKey("line") && routeHashValue["line"] != null ? JsonConvert.DeserializeObject<Geometry>(routeHashValue["line"].ToString()) : null; route.Region = routeHashValue.ContainsKey("region") && routeHashValue["region"] != null ? JsonConvert.DeserializeObject<Geometry>(routeHashValue["region"].ToString()) : null; return route; }
public void Json_RoutePoints() { Route route = new Route(); PointWithMeasure[] points = new PointWithMeasure[2]; PointWithMeasure p1 = new PointWithMeasure(); p1.X = 1; p1.Y = 2; p1.Measure = 2.2; PointWithMeasure p2 = new PointWithMeasure(); p2.X = 1; p2.Y = 2; p2.Measure = 2.3; points[0] = p1; points[1] = p2; route.Points = points; route.Id = 1; route.Length = 3; route.Line = new Geometry(); route.MaxM = 1.3; route.MinM = 0.3; route.Parts = new int[2] { 1, 3 }; route.Region = new Geometry(); route.Style = new Style(); string strroute = Newtonsoft.Json.JsonConvert.SerializeObject(route); Route r1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Route>(strroute); Assert.AreEqual(r1.Points[0].Measure, 2.2); Assert.AreEqual(r1.Points[1].Measure, 2.3); }