WebAPI 2 not deserializing List property o

2019-08-21 10:57发布

问题:

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"
    ]
}

回答1:

Did you try this?

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


回答2:

With thanks to @vc74 and @s.m. , 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.