我試圖從Web API更改json輸出。說我有喜歡的人一個物體,電流輸出會是這樣:ASP.net Web API - 添加陣列名稱到輸出
[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]
但是我想輸出到像:
{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}
如何可以這樣做任何想法呢?
我試圖從Web API更改json輸出。說我有喜歡的人一個物體,電流輸出會是這樣:ASP.net Web API - 添加陣列名稱到輸出
[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]
但是我想輸出到像:
{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}
如何可以這樣做任何想法呢?
選項1 - 創建新模式
而不是返回
public IEnumerable<Person> Get()
回報
public People Get()
其中
public class People {
public IEnumerable<Person> People {get; set;}
}
選項2 - 而不是返回
public IEnumerable<Person> Get()
回報
public dynamic Get() {
IEnumerable<Person> p = //initialize to something;
return new {people = p};
}
方案3的返回動態
- 修改JsonMediaTypeFormatter
您仍然可以返回
public IEnumerable<Person> Get()
但增加了以下類:
public class PeopleAwareJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if ((typeof (IEnumerable<People>).IsAssignableFrom(type)))
{
value = new {people = value};
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
現在WebApiConfig剛剛註冊新的格式,而不是老JSON之一:
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());
您必須具有此JSON
一個DTO
。所以,你必須做的只是爲你的數組提供一個容器。
public class ReturnedJson
{
public IList<People> People {get;set;}
}
public class People
{
public string name {get;set;}
public string sex{get;set;}
}
這是我的假設,你有這個JSON的DTO,因爲你沒有顯示任何代碼。
大廈菲利普W公司的第二個選項,這很好地從數據庫中拉出,因爲名單實現IEnumerable:
公共動態獲取(){
List<Person> personList = new List<Person>(); using (DataTable dt = db.ExecuteDataTable("PeopleSelect")) { foreach (DataRow dr in dt.Rows) { personList.Add(new Person { name = (string)dr["name"], ...}); } } return new { people = personList };
}
讓我們假設變量列表對象的名稱是PersonList
,其返回
[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]
可以根本就返回如下無疼痛
return new
{
people = PersonList
};
那麼你就必須
{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}