Converting a System.Drawing.Point to JSON. How can I convert 'X' and 'Y' to 'x' and 'y'?


December 2018


792 time


I am trying to adhere to the naming conventions in JavaScript as well as in C#. This leads to interesting issues when passing JSONized data back and forth. When I access an x/y coordinate client-side I expect the property to be lowercase, but server-side it is uppercase.


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));

    return Json(polygons, JsonRequestBehavior.AllowGet);

I understand that if I am able to use the C# attribute 'JsonProperty' to customize naming conventions. Yet, as far as I can tell, this is only applicable to classes which I am owner of.

How may I change System.Drawing.Point's properties when passing back to the client?

2 answers


Вы можете обмануть, проецируя в новый анонимный тип:

var projected = polygons.Select(p => new { Vertices = p.Vertices.Select(v => new { x = v.X, y = v.Y }) });

return Json(projected, JsonRequestBehavior.AllowGet);

Как насчет написания собственного преобразователя на основе Json.NET:

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");
                                            new JsonSerializerSettings
                                                    ContractResolver = new CamelCasePropertyNamesContractResolver()

Это будет просто работать для всего приложения, без свойств переименования необходимости (в нижний регистр) в ваших классах в следующем образе: return Json(new { x = ..., y = ...});

И ниже приведен пример использования в действии контроллера:

public virtual NJsonResult GetData()
    var data = ...
    return new NJsonResult(data);