首页 > 解决方案 > 如何将 JSON 发送到使用模型作为来自 HTTPPOST 的 inputParam 的 WEBAPI

问题描述

我在我的 HTTP POST 方法中为我的输入参数定义了一个模型,如下所示

public ActionResult<JObject> Post([FromBody] APIInputObject apiInputObject)

模型看起来像这样

public class APIInputObject
{
    public string ApiKey { get; set; }
    public Brand Brand { get; set; }
    public string Query { get; set; }
    public string Locale { get; set; } = "SE";
    public string UseFormatter { get; set; }
}

品牌部分进一步定义如下

public class Consumer
{
    public string ConsumerName { get; set; }
    public List<Brand> Brands { get; set; }
}

public class Brand
{
    public string BrandName { get; set; }
}

现在的问题是,当我发送 JSON 时,如下所示,我收到一个错误

{
    "apiKey": "xxx",
    "Brand": "xx",
    "query": "showBrand"
}

错误如下

{
    "errors": {
        "Brand": [
            "Error converting value \"xx\" to type 'Pim.Models.Brand'. Path 'Brand', line 3, position 17."
        ]
},

我能做些什么来解决这个错误?

标签: c#json.net

解决方案


您的原始 JSON 格式错误,应采用以下格式:

{
    "apiKey": "xxx",
    "Brand": {
        "BrandName": "xx"
    },
    "query": "showBrand"
}

额外的帮助,对于您的消费者对象,您的 json 格式将如下所示:

{
    "ConsumerName": "xxx",
    "Brands": [{
        "BrandName": "xx1"
    },
    {
        "BrandName": "xx2"
    }]
}

推荐阅读