Skip to main content
 首页 » 编程设计

c#之修改 JSON.NET 的行为以将对象集合序列化为 ID 数组

2024年02月06日30Free-Thinker

我想修改 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.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]}