【发布时间】:2021-01-27 17:12:12
【问题描述】:
假设我有以下 JSON:
{
"name": "Jim",
"age": 20
}
我将其反序列化为以下 C# 对象:
public class Person
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("age")]
public int? Age { get; set; }
[JsonProperty("height")]
public int? Height { get; set; }
}
有什么方法可以确定原始 JSON 中包含哪些属性,哪些属性被省略了?
在这个例子中,我的所有属性都可以为空,JSON 不包含 height 属性,所以我的 C# 对象最终会得到一个 null Height。
但是,用户也可以简单地提供null 作为高度,例如
{
"name": "Jim",
"age": 20,
"height": null
}
所以我的问题是:我是否可以确定是否提供了值但null,或者未提供值因此默认为null。是否有一些可用的元数据在某处/以某种方式为我提供了这些信息?
这是在 ApiController 中使用的,因此反序列化是由 Formatter 自动完成的,但这是我当前的 formatter 设置:
private static void AddFormatter(HttpConfiguration config)
{
var formatter = config.Formatters.JsonFormatter;
formatter.SerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.None
};
}
【问题讨论】:
-
在业务逻辑方面,不提供高度和提供为空的高度有什么区别?
-
这是我用来更新一些其他数据的示例中间对象。最好我只想在初始 JSON 中提供的最终对象上设置字段。
-
@dbc 同意,感谢您的发现!
标签: c# asp.net-web-api json.net .net-framework-4.8