WebAPI 2不在POST请求中反序列化FromBody对象的List <string>属性

时间:2018-02-28 10:43:32

标签: c# asp.net-web-api2 json-deserialization asp.net-apicontroller

在我的一个WebAPI 2应用程序中,我无法反序列化List<string>对象的FromBody属性。 (列表保持为空,而其他属性正确反序列化。)

无论我做什么,如果我将属性更改为string[],该属性似乎只能正确反序列化。对我来说不幸的是,该属性需要是List<string>类型。

根据another question I found,只要List<T>不是T,我就可以反序列化为Interface

有没有人知道我可能做错了什么?

控制器:

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

项目对象类:

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
}

申请JSON:

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

2 个答案:

答案 0 :(得分:1)

你试过这个吗?

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

答案 1 :(得分:0)

感谢@ vc74和@ s.m. ,我设法将我的项目对象类更新为如下所示,使其按照我希望的方式工作:

propOrder

而不是尝试阻止<{1}}来自package main import ( "os" "github.com/Sirupsen/logrus" ) func init() { // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example logrus.SetOutput(os.Stdout) } type logInterface interface { Print() } type MyLogger struct{} func (ml MyLogger) Print() { logrus.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") } func main() { mylogger := MyLogger{} mylogger.Print() } 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 } ,我必须阻止设置价值为null