简体   繁体   中英

WebAPI 2 not deserializing List<string> property of FromBody object in POST request

In one of my WebAPI 2 applications, I'm having trouble deserializing a List<string> property of a FromBody object. (The list stays empty, while the other properties are deserialized correctly.)

Whatever I do, the property only seems to deserialize correctly if I change the property to a string[] . Unfortunately for me, the property needs to be of type List<string> .

According to another question I found , I should be able to deserialize to a List<T> , as long as T is not an Interface .

Is there anyone who has an idea what I could be doing wrong?

Controller:

public class ProjectsController : ApiController
{
    public IHttpActionResult Post([FromBody]Project project)
    {
        // Do stuff...
    }
}

Project object class:

public class Project
{
    public string ID { get; set; }
    public string Title { get; set; }
    public string Details { get; set; }

    private List<string> _comments;
    public List<string> Comments 
    { 
        get
        {
            return _comments ?? new List<string>();
        }
        set
        {
            if (value != _comments)
                _comments = value;
        } 
    }

    public Project () { }

    // Other methods
}

Request JSON:

{
    "Title": "Test",
    "Details": "Test",
    "Comments":
    [
        "Comment1",
        "Comment2"
    ]
}

Did you try this?

public class Project
{
    public List<string> Comments {get; set;}
    public Project () 
    { 
        Comments = new List<string>();
    }
    ...
}

With thanks to @vc74 and @sm , I managed to update my project object class to look like the following to make it work the way I want it to:

public class Project
{
    public string ID { get; set; }
    public string Title { get; set; }
    public string Details { get; set; }

    private List<string> _comments = new List<string>();
    public List<string> Comments 
    { 
        get
        {
            return _comments;
        }
        set
        {
            if (value != _comments)
            {
                if (value == null)
                    _comments = new List<string>();
                else
                    _comments = value;
            }
        } 
    }

    public Project () { }

    // Other methods
}

Instead of trying to prevent getting a null value from Comments , I had to prevent setting the value to null .

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