将System.Drawing.Point转换为JSON.如何转换';X';和';Y';到
本文关键字:转换 Point Drawing System JSON 何转换 | 更新日期: 2023-09-27 18:24:29
我正在努力遵守JavaScript和C#中的命名约定。这会导致在来回传递JSON化数据时出现有趣的问题。当我访问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的属性?
您可以通过投影到一个新的匿名类型中进行作弊:
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");
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);
}