簡體   English   中英

修改JSON.NET的行為以將對象集合序列化為ID數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM