【问题标题】:Web API converted to Azure Mobile Service not serializing all properties转换为 Azure 移动服务的 Web API 未序列化所有属性
【发布时间】:2016-10-02 00:34:39
【问题描述】:

我有一个正在工作的 Web API,我正在将其转换为 .Net Azure 移动服务。 API 返回一个复杂的模型——具有属性的对象——其中一些是其他对象的集合。这在普通 Web API 中可以正常工作,但在 Azure 移动服务中,我的一个模型没有序列化所有属性。

当我在控制器中的 return 语句上设置断点时,我看到所有属性及其值都存在。这让我相信问题出在序列化 (JSON) 上。

return Request.CreateResponse(HttpStatusCode.OK, myModel);

正在序列化的属性示例:

public Guid Id { get; set; }
public IEntityDto ModelDto { get; set; } //this is an object with many properties all of which serialize

未序列化的属性示例:

public ItemStatus Status { get; set; }  //this is an enum
public string Message { get; set; }
public string TestProp { get; set; } //this is a simple string property I added to help debug

我怎样才能进一步调试这个,以便我可以看到为什么这些属性被排除在外?

注意:目前我仍在本地运行,而不是在 Azure 之外运行。这适用于 Visual Studio 2013 Update 2 RTM。

更新:经过仔细检查,未序列化的属性似乎是枚举或值为 null 的属性。

【问题讨论】:

  • 你不想发布哪些属性是序列化的,哪些不是。还是您希望我们盲目猜测。
  • 我已更新问题以包含示例属性。我实际上只是在寻找有关如何调试序列化程序的指导,但您对更多信息的推动使我注意到有问题的属性要么是枚举,要么值为 null。
  • 枚举属性的值是否有枚举的默认值?默认情况下,JSON 序列化程序不会使用默认值序列化这些字段(对象类型中的 null 就是这种情况)。
  • @carlosfigueira 就是这样!对于任何阅读的人,可以通过设置更改此行为:HttpConfiguration.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling
  • 您能否发表您的评论作为答案(并接受它),以便其他人可以从您所做的事情中学习?谢谢!

标签: c# .net visual-studio asp.net-web-api azure-mobile-services


【解决方案1】:

正如@carlosfigueira 在对原始问题的评论中提到的那样,JSON 序列化程序的默认行为是排除具有 null 和默认值的属性。为了解决这个问题,我更改了以下设置:

  httpConfig.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
  httpConfig.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

...其中httpConfig 的类型为HttpConfiguration。您可以在应用启动时进行这些更改 - 在 WebApiConfig.cs 等配置文件中或直接在 Global.asax.cs 中进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多