在我的一个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"
]
}
你试过这个吗?
public class Project
{
public List<string> Comments {get; set;}
public Project ()
{
Comments = new List<string>();
}
...
}
感谢@ vc74和@ s.m. ,我设法将我的项目对象类更新为如下所示,使其按照我希望的方式工作:
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
获得Comments
值,我不得不阻止将值设置为null
。