Convert System.Drawing.Point to JSON. How to convert "X" and "Y" to "x" and "y"?

I am trying to stick to naming conventions in both JavaScript and C #. This leads to interesting questions when passing JSONized data back and forth. When I access the client side of the x / y coordinate, I expect the property to be lowercase, and on the server side in uppercase.

Note:

public class ComponentDiagramPolygon { public List<System.Drawing.Point> Vertices { get; set; } public ComponentDiagramPolygon() { Vertices = new List<System.Drawing.Point>(); } } public JsonResult VerticesToJsonPolygon(int componentID) { PlanViewComponent planViewComponent = PlanViewServices.GetComponentsForPlanView(componentID, SessionManager.Default.User.UserName, "image/png"); ComponentDiagram componentDiagram = new ComponentDiagram(); componentDiagram.LoadComponent(planViewComponent, Guid.NewGuid()); List<ComponentDiagramPolygon> polygons = new List<ComponentDiagramPolygon>(); if (componentDiagram.ComponentVertices.Any()) { ComponentDiagramPolygon polygon = new ComponentDiagramPolygon(); componentDiagram.ComponentVertices.ForEach(vertice => polygon.Vertices.Add(vertice)); polygons.Add(polygon); } return Json(polygons, JsonRequestBehavior.AllowGet); } 

I understand that if I can use the C # attribute 'JsonProperty' to set up naming conventions. However, as far as I can tell, this only applies to the classes that I am.

How can I change the properties of System.Drawing.Point when passing back to the client?

+4
source share
2 answers

You can trick by projecting a new anonymous type:

 var projected = polygons.Select(p => new { Vertices = p.Vertices.Select(v => new { x = vX, y = vY }) }); return Json(projected, JsonRequestBehavior.AllowGet); 
+2
source

How about writing your own Json.NET-based converter:

 public class NJsonResult : ActionResult { private object _obj { get; set; } public NJsonResult(object obj) { _obj = obj; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.AddHeader("content-type", "application/json"); context.HttpContext.Response.Write( JsonConvert.SerializeObject(_obj, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })); } } 

This will only work for your entire application without the need to rename properties (lowercase) in your classes as follows: return Json(new { x = ..., y = ...});

And below is an example of using a controller in an action:

 [AcceptVerbs(HttpVerbs.Get)] public virtual NJsonResult GetData() { var data = ... return new NJsonResult(data); } 
0
source

Source: https://habr.com/ru/post/1396518/


All Articles