Json.net 反序列化,子属性为空时作为数组出现
Json.net deserialization, child properties that come as an array when empty
我正在与可以 return 以下 JSON 结构的网络服务对话:
{
"foo": {
"bar": "hello world"
}
}
Foo 是可选的,但我们得到的不是 NULL 值:
{
"foo": []
}
空数组。
我通过在我的模型中使用以下属性来使用(丑陋的)解决方法:
public dynamic Foo { get; set; }
public FooModel FooObject {
get
{
if(Foo == null || Foo.GetType().IsArray)
{
return null;
}
return ((JObject)Foo).ToObject<FooModel>();
}
}
这适用于这首单曲 属性。但是 web 服务对所有为 NULL 的对象执行此操作。我正在寻找一种在反序列化时忽略所有空数组的通用解决方案。 (或其他)
我一直没能找到解决办法。我尝试研究使用自定义 JsonConverter 和 ContractResolver。
避免该问题的一个简单方法是将 JSON 预加载到 JToken
then remove all empty array properties using the extension method RemoveEmptyArrayProperties
from to :
public static class JsonExtensions
{
public static TJToken RemoveEmptyArrayProperties<TJToken>(this TJToken root) where TJToken : JToken
{
var container = root as JContainer;
if (container == null)
return root;
var query = container.DescendantsAndSelf()
.OfType<JProperty>()
.Where(p => p.Value is JArray && ((JArray)p.Value).Count == 0);
foreach (var property in query.ToList())
{
property.Remove();
}
return root;
}
}
根据该方法,您可以按如下方式预处理 JSON 字符串:
var root = JObject.Parse(jsonString)
.RemoveEmptyArrayProperties()
.ToObject<RootObject>();
.Net 工作示例 fiddle here.
我正在与可以 return 以下 JSON 结构的网络服务对话:
{
"foo": {
"bar": "hello world"
}
}
Foo 是可选的,但我们得到的不是 NULL 值:
{
"foo": []
}
空数组。 我通过在我的模型中使用以下属性来使用(丑陋的)解决方法:
public dynamic Foo { get; set; }
public FooModel FooObject {
get
{
if(Foo == null || Foo.GetType().IsArray)
{
return null;
}
return ((JObject)Foo).ToObject<FooModel>();
}
}
这适用于这首单曲 属性。但是 web 服务对所有为 NULL 的对象执行此操作。我正在寻找一种在反序列化时忽略所有空数组的通用解决方案。 (或其他)
我一直没能找到解决办法。我尝试研究使用自定义 JsonConverter 和 ContractResolver。
避免该问题的一个简单方法是将 JSON 预加载到 JToken
then remove all empty array properties using the extension method RemoveEmptyArrayProperties
from
public static class JsonExtensions
{
public static TJToken RemoveEmptyArrayProperties<TJToken>(this TJToken root) where TJToken : JToken
{
var container = root as JContainer;
if (container == null)
return root;
var query = container.DescendantsAndSelf()
.OfType<JProperty>()
.Where(p => p.Value is JArray && ((JArray)p.Value).Count == 0);
foreach (var property in query.ToList())
{
property.Remove();
}
return root;
}
}
根据该方法,您可以按如下方式预处理 JSON 字符串:
var root = JObject.Parse(jsonString)
.RemoveEmptyArrayProperties()
.ToObject<RootObject>();
.Net 工作示例 fiddle here.