使用JsonProperty将JSON转换为Model属性 [英] JSON to Model property binding using JsonProperty

查看:370
本文介绍了使用JsonProperty将JSON转换为Model属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我受我的聚会和客户端之间的协议约束,可以使用包含破折号的json参数.由于无法在C#的属性名称中使用该属性,因此我需要映射到所需的属性.

I'm bound by agreements between my party and the client to use json parameters containing dashes. Since it's not possible to use that in property names in C#, I need to map to the desired property.

我现在要做什么:

为方便起见,以下代码经过简化.

The below code is simplified for convenience.

模型

public class MyRequest
{
    [JsonProperty("request-number")]
    public string RequestNumber { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

控制器

[HttpGet]
[Route("api/load-stuff")]
public Stuff LoadStuff([FromUri]MyRequest request)
{
    return BackEnd.LoadStuff(request);
}

从客户端调用API

使用此uri定位上述控制器:

The above controller is targeted using this uri:

http://localhost:12345/api/load-stuff?request-number=X123&name=requestName

我的问题

如果我在BackEnd.LoadStuff行上设置一个断点,我可以看到调用已到达,但请求未正确映射.

If I put a breakpoint at the BackEnd.LoadStuff line I can see the call arrives, but the request isn't mapped correctly.

名称包含我期望的内容:requestName,但是RequestNumber是null,因此映射无法正常工作.

Name contains what I expect: requestName, but RequestNumber is null, so the mapping didn't work.

怎么了?

推荐答案

在尝试将请求参数绑定到模型时,ASP.NET的默认模型绑定器未考虑JsonPropertyAttribute,这是不能的,因为不了解JsonPropertyAttribute和NewtonSoft.Json的其余部分.根据您的情况(在C#中不是合法标识符的属性名称),实现您想要的唯一方法是通过自定义模型绑定器会读取JsonPropertyAttribute.

ASP.NET's default model binder doesn't take the JsonPropertyAttribute into account when attempting to bind request parameters to a model (it can't, since it doesn't know about JsonPropertyAttribute and the rest of NewtonSoft.Json). Given your scenario (property names that aren't legal identifiers in C#), the only way to achieve what you want is via a custom model binder that does read JsonPropertyAttribute.

如果您确实具有合法的属性名称(例如request_number),则可以使用这些已命名的属性创建一个请求模型,然后将其映射到具有正确命名的属性的单独模型,例如:

If you did have property names that were legal identifiers (for example request_number) then you could create a request model with those named properties, then map it to a separate model with the correctly-named properties, e.g.:

public class MyController : ApiController
{
    [HttpGet]
    [Route("api/load-stuff")]
    public Stuff LoadStuff([FromUri]MyRequest request)
    {
        return BackEnd.LoadStuff(request.ToMyPrettyRequest());
    }
}

public class MyRequest
{
    public string request_number { get; set; }

    public string name { get; set; }

    MyPrettyRequest ToMyPrettyRequest()
    {
        return new MyPrettyRequest
        {
            RequestNumber = request_number,
            Name = name,
        };
    }
}

public class MyPrettyRequest
{
    public string RequestNumber { get; set; }

    public string Name { get; set; }
}

这篇关于使用JsonProperty将JSON转换为Model属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆