我想修改JSON。. NET,以便当我从我的API序列化一个模型时,它只发送一个复合集合对象的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实现这一点。净序列化器吗?
您可以使用自定义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。净的文档。
public class Address
{
[JsonProperty("Id")]
public int I'd { get; set; }
[JsonIgnore]
public string Location { get; set; }
[JsonIgnore]
public string PostalCode { get; set; }
}
唯一的缺点是,你永远无法序列化的位置和PostalCode属性JSON,即使你想。
我相信有一种方法可以指定在使用Json.Net序列化到JSON时应该使用的序列化。同样,请查看他们的文档