Search code examples
asp.netasp.net-web-apijson.netdatacontract

DataContract Name Attribute not Working with Json Serializer


I'm building a JSON only WepApi and I have a controller which returns a list. I have decorated the list with Datacontract/Datamember attributes like this:

[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;
       }
   }

In my controller I return the list like this:

// 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;

But in the JSON output the Name attribute for the list is missing:

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

To force JSON-only output i have removed the xml formatter on Global.asax:

//Only JSON
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);

Thanks in advance


Solution

  • Arrays don't have names by themselves in JSON. If you want a name on the list, you need an outer object that has a named property to hold the list.

    Something like this:

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

    The JSON would then look like this:

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