I have the following model:
public class DocumentViewModel
{
public long Id { get; set; }
public long? ParentFolderId { get; set; }
public bool IsFolder { get; set; }
public bool IsImage { get; set; }
}
and the following API Controller:
public HttpResponseMessage GetChildren(long jobId, long folderId)
{
using (var model = DatabaseHelper.GetModel())
{
var accessLevel = MembershipHelper.GetLoggedInAccessLevel(model);
List<DocumentViewModel> documents = DocumentHelper.GetDocumentsForMobile(model, jobId, folderId, accessLevel).ToList();
return this.Request.CreateResponse(
HttpStatusCode.OK,
new { data = documents });
}
}
The problem is that IsFolder and IsImage are missing from the json when I review this in Fiddler when they are set to false. They show up fine when they are set to true.
I suspect this is because .Net thinks true is the default value, and excludes fields where the value is the same as the default.
How do I tell .Net to ALWAYS include this value, regardless?
In the Register
method of the WebApiConfig
class (located in the App_Start
folder) try adding this line:
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling =
Newtonsoft.Json.DefaultValueHandling.Include;
This should force Web Api to include default values if it isn't already.
EDIT
If you're using an older version of Web API that does not have a WebApiConfig, you can also do this in the Application_Start
method in Global.asax.cs
:
var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.