我正在实现一个使用JSON.NET进行序列化的WebAPI2服务。
当我尝试放入(反序列化)更新的json数据时,抽象类不存在,这意味着它不知道如何处理它,所以它什么也不做。我还试着让类不是抽象的,只是继承它,然后每个PUT都应该放到基类,而不是derrived类,缺少derrived类的属性。
示例:
public class People
{
// other attributes removed for demonstration simplicity
public List<Person> People { get;set; }
}
public abstract class Person
{
public string Id {get;set;}
public string Name {get;set;}
}
public class Employee : Person
{
public string Badge {get;set;}
}
public class Customer : Person
{
public string VendorCategory {get;set;}
}
将我的web api配置为执行typename处理:
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling =
TypeNameHandling.Objects;
}
然后我把JSON放在下面:
{
people: [{
name: "Larry",
id: "123",
badge: "12345",
$type: "API.Models.Employee, API"
}]
}
对web api方法执行以下操作:
public HttpResponseMessage Put(string id, [FromBody]People value)
{
people.Update(value); // MongoDB Repository method ( not important here )
return Request.CreateResponse(HttpStatusCode.OK);
}
但在检查value
时,输出始终是:
People == { People: [] }
或者如果是非抽象的:
People == { People: [{ Name: "Larry", Id: "123" }] }
缺少继承的属性。有没有人遇到这个问题,想出了什么办法?
发布于 2013-12-10 03:04:47
$type
函数必须是对象中的第一个属性。
在上面的例子中,我做到了:
{
people: [{
name: "Larry",
id: "123",
badge: "12345",
$type: "API.Models.Employee, API"
}]
}
将$type
移到顶部后,如下所示:
{
people: [{
$type: "API.Models.Employee, API",
name: "Larry",
id: "123",
badge: "12345"
}]
}
序列化程序能够将对象反转换为正确的强制转换。一定会喜欢的!
发布于 2013-12-06 03:48:12
我现在已经尝试了你的方案,它工作得很好。但我确实注意到,您的json输入中的id
属性后面缺少了一个,
(逗号)。
我通过在我的操作中使用下面的ModelState有效性检查来解决这个问题,然后它会显示我的请求负载中的错误。这也可能对你有用:
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState);
}
发布于 2015-02-24 15:28:26
我知道这篇文章已经过时了,答案也已经标注出来了,但我想我的解决方案可能会有所帮助……
尝试将JsonProperty属性添加到抽象类的属性中。
using JTC.Framework.Json;
...
public class People
{
// other attributes removed for demonstration simplicity
public List<Person> People { get;set; }
}
public abstract class Person
{
[JsonProperty()]
public string Id {get;set;}
[JsonProperty()]
public string Name {get;set;}
}
public class Employee : Person
{
public string Badge {get;set;}
}
public class Customer : Person
{
public string VendorCategory {get;set;}
}
https://stackoverflow.com/questions/20408771
复制相似问题