2012-02-14 158 views
4

我想遵守JavaScript以及C#中的命名约定。当来回传递JSON化数据时,这会引发一些有趣的问题。当我访问x/y坐标客户端时,我期望该属性是小写字母,但服务器端是大写字母。将System.Drawing.Point转换为JSON。如何将'X'和'Y'转换为'x'和'y'?

观察:

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

我明白,如果我能够使用C#属性“JsonProperty”自定义命名约定。然而,据我所知,这只适用于我所拥有的课程。

如何在传递回客户端时更改System.Drawing.Point的属性?

+0

如果您使用的是JsonProperty,那么您使用的是JSON.NET,而不是股票'JavaScriptSerializer';是这样吗? – 2012-02-14 22:35:50

+0

是的。对JSON.NET的引用已经包含在项目中 - 在这种情况下,我还没有使用它(还)。 – 2012-02-14 22:38:13

+0

这几天前似乎类似于这个问题:http://stackoverflow.com/questions/9247478/pascal-case-dynamic-properties-with-json-net/9247705#9247705。 – 2012-02-14 22:48:36

回答

2

你可以欺骗,通过投射到一个新的匿名类型:

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

return Json(projected, JsonRequestBehavior.AllowGet); 
0

如何编写自己的基于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"); 
     context.HttpContext.Response.Write(
       JsonConvert.SerializeObject(_obj, 
              Formatting.Indented, 
              new JsonSerializerSettings 
               { 
                ContractResolver = new CamelCasePropertyNamesContractResolver() 
               })); 
    } 
} 

这将只为您的整个应用程序的工作,没有属性在你的类中按以下方式重新命名(小写):return Json(new { x = ..., y = ...});

以下是控制器操作中的用法示例:

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