我正在构建一个只支持JSON的WepApi,我有一个返回列表的控制器。我用Datacontract/Datamember属性装饰了列表,如下所示:
[DataContract(Name = "Files", Namespace = "http://schemas.example.com")]
public class FileDesc
{
[DataMember(Name = "MyFileName")]
public string Name { get; set; }
[DataMember(Name = "MyFilePath")]
public string Path { get; set; }
[DataMember(Name = "MyFileSize")]
public long? Size { get; set; }
public FileDesc(string n, string p, long? s)
{
Name = n;
Path = p;
Size = s;
}
}
在我的控制器中,我返回如下列表:
// Response
List<FileDesc> FileList = new List<FileDesc>();
foreach (MultipartFileData file in provider.FileData)
{
FileList.Add(new FileDesc(file.Headers.ContentDisposition.FileName, file.LocalFileName , file.Headers.ContentDisposition.Size ));
}
return FileList;
但在JSON输出中,缺少列表的Name属性:
[
{
"myFileName": ""ArduinoUNO.png"",
"myFilePath": "c:\images\ArduinoUNO.png",
"myFileSize": null
}
]
为了强制只输出JSON,我删除了Global.asax:上的xml格式化程序
//Only JSON
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
提前感谢
数组本身在JSON中没有名称。如果要在列表中显示名称,则需要一个具有命名属性的外部对象来保存列表。
类似这样的东西:
public class Response
{
[DataMember(Name = "Files")]
List<FileDesc> FileList { get; set; }
}
JSON看起来是这样的:
{
"Files":
[
{
"myFileName": ""ArduinoUNO.png"",
"myFilePath": "c:\images\ArduinoUNO.png",
"myFileSize": null
}
]
}