[英]Modify the behaviour of JSON.NET to serialize a collection of objects to an array of IDs
我想修改JSON.NET,以便从我的API序列化模型时,它只为复合Collection对象发送ID数组。
例如:
class Employee
{
public ICollection<Address> Addresses { get; set; }
}
class Address
{
public int id;
public string location;
public string postcode;
}
然后当我通过WebApi发送回去时
Request.Createresponse(HttpStatusCode.OK, new Employee());
代替这个:
{
"Addresses" :
[
{"id" : 1, "location" : "XX", "postcode" : "XX" },
{"id" : 2, "location" : "XX", "postcode" : "XX" }
]
}
它只是这样发送:
{
"Addresss" : [1,2]
}
我希望这种情况在整个应用程序范围内发生,并且我不想在特定位置进行修改。
如何使用JSON.NET序列化程序实现此目的?
您可以使用以下自定义JsonConverter
获得所需的结果:
class IdOnlyListConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (typeof(IEnumerable).IsAssignableFrom(objectType) &&
objectType != typeof(string));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JArray array = new JArray();
foreach (object item in (IEnumerable)value)
{
PropertyInfo idProp = item.GetType().GetProperty("id");
if (idProp != null && idProp.CanRead)
{
array.Add(JToken.FromObject(idProp.GetValue(item, null)));
}
}
array.WriteTo(writer);
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
在模型中,只要您有只需要ID的东西的集合,就可以使用[JsonConverter]
属性装饰该集合属性,该属性指定了自定义转换器。 例如:
class Employee
{
public string name { get; set; }
[JsonConverter(typeof(IdOnlyListConverter))]
public ICollection<Address> Addresses { get; set; }
}
class Address
{
public int id { get; set; }
public string location { get; set; }
public string postcode { get; set; }
}
当集合被序列化时,将使用转换器,并且仅ID值将被写出。 演示:
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee
{
name = "Joe",
Addresses = new List<Address>
{
new Address { id = 1, location = "foo", postcode = "bar" },
new Address { id = 2, location = "baz", postcode = "quux" }
}
};
string json = JsonConvert.SerializeObject(emp);
Console.WriteLine(json);
}
}
输出:
{"name":"Joe","Addresses":[1,2]}
请查看Json.Net的文档。
public class Address
{
[JsonProperty("Id")]
public int I'd { get; set; }
[JsonIgnore]
public string Location { get; set; }
[JsonIgnore]
public string PostalCode { get; set; }
}
这样做的唯一缺点是,您将永远无法将Location和PostalCode属性序列化为JSON。
我相信有一种方法可以指定使用Json.Net序列化为JSON时应使用的序列化。 再次查看其文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.