Objects exposed on JSON web-api - how to stop the

2020-04-10 01:32发布

I have an object model that looks like:

public class Product
{
    public string ProductCode { get; set; }
    public string ProductInfo { get; set; }
}

I'm populating this via Dapper, and exposing it to an angular.js consumer, but the property names in the JSON are coming out as:

{
     "productCode": 1,
     "productInfo": "Product number 1"
}

Note in particular the camel-case. I would like it to match the original declared names, i.e.

{
     "ProductCode": 1,
     "ProductInfo": "Product number 1"
}

How can I do this?

1条回答
放我归山
2楼-- · 2020-04-10 02:06

Under the hood, it is most likely that the web-API is using JSON.Net as the JSON serialization engine; this means that you can control the output using JSON.Net's attributes, for example:

public class Product
{
    [JsonProperty("ProductCode")]
    public string ProductCode { get; set; }
    [JsonProperty("ProductInfo")]
    public string ProductInfo { get; set; }
}

Without these, JSON.Net uses conventions and configuration - and the usual JSON convention is to use camel-case, hence that is the default. You can also probably change the default configuration, but I would advise against that unless you understand the scope of the impact.

查看更多
登录 后发表回答