将对象绑定到Web API端点时指定自定义属性名称 [英] Specifying custom property name when binding object to Web API endpoint

查看:116
本文介绍了将对象绑定到Web API端点时指定自定义属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.Net Core Web API.当模型属性与请求主体匹配时,它将自动映射模型.例如,如果您有此类:

I have a .Net Core Web API. It automatically maps models when the model properties match the request body. For example, if you have this class:

public class Package
{
    public string Carrier { get; set; }
    public string TrackingNumber { get; set; }
}

如果请求正文为以下JSON,它将正确地将其绑定到POST端点:

It would correctly bind it to a POST endpoint if the request body is the following JSON:

{
    carrier: "fedex",
    trackingNumber: "123123123"
}

我需要做的是指定要映射的自定义属性.例如,使用上面的同一类,如果TrackingNumber以tracking_number的形式出现,我需要能够映射到JSON.

What I need to do is specify a custom property to map. For example, using the same class above, I need to be able to map to JSON if the TrackingNumber comes in as tracking_number.

我该怎么做?

推荐答案

更改您的包类,并为要映射到不同json字段的每个字段添加JsonProperty装饰.

Change your package class and add JsonProperty decoration for each field you wish to map to a different json field.

public class Package
{
    [JsonProperty(PropertyName = "carrier")]
    public string Carrier { get; set; }

    [JsonProperty(PropertyName = "trackingNumber")]
    public string TrackingNumber { get; set; }
}

这篇关于将对象绑定到Web API端点时指定自定义属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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