简体   繁体   中英

How to send JSON into a WEBAPI that uses a model as inputParam from the HTTPPOST

I have defined a model for my input parameter in my HTTP POST method like this

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

The Model looks like this

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; }
}

The Brand part is further defined like this

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

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

The problem is now that when I send JSON is that looks like below I get an error

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

The error is as follows

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

What can I do to fix this error?

Your original JSON formatting is wrong it should be in the following format:

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

Bonus help, for your consumer object your json format would be like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM