[英]webapi not recognize json list
I've got a list of objects in JSON that isn't recognized by a WebApi2 controller 我有一个WebApi2控制器无法识别的JSON对象列表
The JSON list is the following: JSON列表如下:
{
"FirstObjectType": [{"Name": "the_name"}],
"SecondObjectType": [{"Label": "01_obj"}, {"Label": "02_obj"}]
}
The Model class is: Model类是:
public class CompositeObject
{
[JsonProperty("FirstObjectType")]
public List<FirstObject> fo { get; set; }
[JsonProperty("SecondObjectType")]
public List<SecondObject> so { get; set; }
}
The controller is: 控制器是:
public IHttpActionResult PostList([FromBody] CompositeObject jsonList)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
List<FirstObject> fo_list = jsonList.fo;
foreach (var item in fo_list)
{
db.FirstObject.Add(item);
db.SaveChanges();
}
return StatusCode(HttpStatusCode.OK);
}
When I submit the Post action, the controller recognize both lists in CompositeObject jsonList as Null 当我提交Post操作时,控制器将CompositeObject jsonList中的两个列表都识别为Null
There is a problem in your model, where names are not being matched. 您的模型中存在一个问题,其中名称不匹配。 You have to update model as: 您必须将模型更新为:
public class FirstObjectType
{
public string Name { get; set; }
}
public class SecondObjectType
{
public string Label { get; set; }
}
public class RootObject
{
public List<FirstObjectType> FirstObjectType { get; set; }
public List<SecondObjectType> SecondObjectType { get; set; }
}
I have assumed that FirstObjectType
contains string with name Name
and SecondObjectType
contains string with name Label
. 我假设FirstObjectType
包含名称为Name
字符串, SecondObjectType
包含名称为Label
字符串。 Make sure to use same names for properties of FirstObjectType
and SecondObjectType
class as in JSON string. 确保对FirstObjectType
和SecondObjectType
类的属性使用与JSON字符串相同的名称。
The issue was in the client code because I missed to set the Content-type as application/json
in the header section. 问题出在客户端代码中,因为我错过了在标头部分中将Content-type设置为application/json
的问题。
In this way the WebApi server doesn't recognize in the right way the JSON object (I think that the server look for a x-www-form-urlencoded type) 这样,WebApi服务器无法以正确的方式识别JSON对象(我认为服务器正在寻找x-www-form-urlencoded类型)
So, the code above is right, but I have found another solution 所以,上面的代码是正确的,但是我找到了另一个解决方案
In the WebApi controller: 在WebApi控制器中:
using Newtonsoft.Json.Linq;
public IHttpActionResult PostList([FromBody] JObject ReceivedObjectsList)
{
var receivedLists = ReceivedObjectsList.Properties();
List<FirstObject> fo = ReceivedObjectsList["FirstObjectType"].ToObject<List<FirstObject>>();
List<SecondObject> so = ReceivedObjectsList["SecondObjectType"].ToObject<List<SecondObject>>();
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.