簡體   English   中英

ASP.NET Web API部分響應Json序列化

[英]ASP.NET Web API partial response Json serialization

我正在實現支持部分響應的Web API。

/api/users?fields=id,name,age

鑒於用戶類

[JsonObject(MemberSerialization.OptIn)]
public partial class User
{
  [JsonProperty]
  public int id { get; set; }

  [JsonProperty]
  public string firstname { get; set; }

  [JsonProperty]
  public string lastname { get; set; }

  [JsonProperty]
  public string name { get { return firstname + " " + lastname; } }

  [JsonProperty]
  public int age { get; set; }
}

在序列化所有屬性時,Json格式化程序工作得很好,但我無法在運行時修改它以告訴它忽略某些屬性,具體取決於查詢參數“fields”。

我正在使用JsonMediaTypeFormatter。

我已經關注http://tostring.it/2012/07/18/customize-json-result-in-web-api/以自定義格式化程序,但我找不到任何關於如何強制格式化程序的示例忽略一些屬性。

創建自己的IContractResolver告訴JSON.NET需要序列化哪些屬性。 在官方文檔中有一個例子,你可以從中獲取靈感

只是添加到這里的回復; 我找到了一個為你做這個的nuget包

WebApi.PartialResponse

Git hub源代碼:
https://github.com/dotarj/PartialResponse

它基本上包裝了上面討論的格式化程序,因此您只需要像這樣配置它:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new PartialJsonMediaTypeFormatter() { IgnoreCase = true });

然后,您可以在請求中指定?fields=<whatever> ,它將返回僅指定了那些字段的模型。

您還可以通過添加與屬性同名的布爾方法來有條件地序列化屬性,然后使用ShouldSerialize為方法名稱添加前綴。 方法的結果確定屬性是否已序列化。 如果該方法返回true,則該屬性將被序列化,如果它返回false並且將跳過該屬性。

public class Employee
{
  public string Name { get; set; }
  public Employee Manager { get; set; }

  public bool ShouldSerializeManager()
  {
      // don't serialize the Manager property if an employee is their own manager
      return (Manager != this);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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