【问题标题】:DataContract Name Attribute not Working with Json SerializerDataContract 名称属性不适用于 Json 序列化程序
【发布时间】:2013-06-24 17:00:22
【问题描述】:

我正在构建一个仅 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 输出中,列表的名称属性缺失:

[
  {
    "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);

提前致谢

【问题讨论】:

    标签: asp.net asp.net-web-api json.net datacontract


    【解决方案1】:

    数组本身在 JSON 中没有名称。如果您想要列表中的名称,则需要一个具有命名属性的外部对象来保存列表。

    类似这样的:

    public class Response
    {
        [DataMember(Name = "Files")]
        List<FileDesc> FileList { get; set; }
    }
    

    JSON 将如下所示:

    {
        "Files": 
        [
            {
                "myFileName": "\"ArduinoUNO.png\"",
                "myFilePath": "c:\\images\\ArduinoUNO.png",
                "myFileSize": null
            }
        ]
    }
    

    【讨论】:

    • 谢谢你,这正是我想要的。我刚刚开始使用 JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2013-10-11
    • 2013-10-09
    相关资源
    最近更新 更多