相关疑难解决方法(0)

MVC JsonResult camelCase序列化

我试图让我的动作返回一个JsonResult,其所有属性都在camelCase中.

我有一个简单的模型:

public class MyModel
{
    public int SomeInteger { get; set; }

    public string SomeString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

一个简单的控制器动作:

public JsonResult Index()
    {
        MyModel model = new MyModel();
        model.SomeInteger = 1;
        model.SomeString = "SomeString";

        return Json(model, JsonRequestBehavior.AllowGet);
    }
Run Code Online (Sandbox Code Playgroud)

现在调用此操作方法将返回包含以下数据的JsonResult:

{"SomeInteger":1,"SomeString":"SomeString"}
Run Code Online (Sandbox Code Playgroud)

对于我的用途我需要动作返回camelCase中的数据,不知何故这样:

{"someInteger":1,"someString":"SomeString"}
Run Code Online (Sandbox Code Playgroud)

有没有优雅的方法来做到这一点?

我正在寻找可能的解决方案,并找到MVC3 JSON序列化:如何控制属性名称?他们将DataMember定义设置为模型的每个属性,但我真的不想这样做.

我还找到了一个链接,他们说可以解决这类问题:http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-序列化#json_camelcasing.它说:

要使用camel大小写来编写JSON属性名,而不更改数据模型,请在序列化程序上设置CamelCasePropertyNamesContractResolver:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Run Code Online (Sandbox Code Playgroud)

此博客上的一个条目http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/也提到了这个解决方案并声明您可以简单地将其添加到RouteConfig.RegisterRoutes来解决此问题.我尝试过,但我无法使它工作.

你们有什么想法我做错了吗?

asp.net-mvc serialization json camelcasing

31
推荐指数
2
解决办法
3万
查看次数

在控制器中的ActionResult上使用ActionFilter返回JsonResult

我想使用ActionFilter以不同的格式(JavaScript/XML/JSON/HTML)返回控制器的Model(数据).这是我到目前为止的地方:

ActionFilter:

public class ResultFormatAttribute : ActionFilterAttribute, IResultFilter
{
    void IResultFilter.OnResultExecuting(ResultExecutingContext context)
    {
        var viewResult = context.Result as ViewResult;

        if (viewResult == null) return;

        context.Result = new JsonResult { Data = viewResult.ViewData.Model };
    }
}
Run Code Online (Sandbox Code Playgroud)

它的实施:

[ResultFormat]
public ActionResult Entries(String format)
{
    var dc = new Models.WeblogDataContext();

    var entries = dc.WeblogEntries.Select(e => e);

    return View(entries);
}
Run Code Online (Sandbox Code Playgroud)

OnResultExecuting方法被调用,但我没有得到返回的Model(数据)并将其格式化为JSON对象.我的控制器只是呈现视图.


更新:我遵循达林迪米特洛夫对这个问题的回答的建议.

c# asp.net-mvc

8
推荐指数
1
解决办法
8148
查看次数

标签 统计

asp.net-mvc ×2

c# ×1

camelcasing ×1

json ×1

serialization ×1