【发布时间】:2015-12-02 14:59:23
【问题描述】:
我正在使用 CodeFluent JsonUtilities 将对象转换为 JSON。使用其他任何东西似乎都有其他各种问题(例如循环引用)。
以下是我使用 CodeFluent.Runtime.Utilities 命名空间(用于 JsonUtilities)转换为 ASP.NET MVC 的 JSON 的一些函数。
public static ContentResult ConvertToJsonResponse(object obj)
{
string json = JsonUtilities.Serialize(obj);
return PrepareJson(json);
}
/// <summary>
/// Converts JSON string to a ContentResult object suitable as a response back to the client
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static ContentResult PrepareJson(string json)
{
ContentResult content = new ContentResult();
content.Content = json;
content.ContentType = "application/json";
return content;
}
问题是当我使用 JsonUtilities 转换对象时,它似乎跳过了一些嵌套对象。
例如,我尝试使用 CodeFluent 将 DataSourceResult 对象(来自 Telerik)转换为 JSON。
public ActionResult UpdateTeam([DataSourceRequest]DataSourceRequest request, TeamViewModel teamViewModel)
{
ModelState.AddModelError("", "An Error!");
DataSourceResult dataSourceResult = new[] { teamViewModel }.ToDataSourceResult(request, ModelState);
ContentResult ret = CodeFluentJson.ConvertToJsonResponse(dataSourceResult);
return ret;
}
dataSourceResult 包含三个主要属性:
- Data - 包含我的模型,其中包含我的数据。
- Total - 包含数据对象的数量。
- Errors - 包含我的 MVC 模型的所有错误。它非常嵌套,下面有很多属性。
当我尝试使用 CodeFluent 实用程序转换 DataSourceResult 对象时,它可以转换“Data”和“Total”字段,但如果出现错误,它会完全跳过它,从而产生以下 JSON 字符串:
{
"Data":[
{
"ExampleProperty":"ExampleValue"
}
],
"Total":1,
"AggregateResults":null,
"Errors":{ }
}
我猜测问题在于“错误”对象对于 CodeFluent 转换器而言嵌套过多。 所以我的问题是我是否缺少任何 CodeFluent 序列化选项/代码来处理 JSON 转换的重度嵌套对象?
【问题讨论】:
-
你能详细说明 DataSourceResult 是什么类吗?来自什么 Telerik 产品?
-
查看此链接:doylestowncoder.wordpress.com/2014/04/14/… Telerik DataSourceResult 对象来自 Telerik ASP.NET MVC。它是一个默认类,用于格式化我的响应以发送到 Telerk ASP.NET MVC Grid(可能还有其他使用 DataSource 对象的控件)。对于我的 MVC 网格上的读取操作,它会执行我所有的分页、排序、过滤和格式化我的模型对象和模型状态错误,以将其发送回 MVC 网格,以便它处理 CRUD 操作。对于创建/更新/删除,据我所知,它主要用于错误处理目的。
标签: json model-view-controller telerik codefluent