【问题标题】:Json.net deserialization, child properties that come as an array when emptyJson.net 反序列化,空时作为数组出现的子属性
【发布时间】:2018-06-05 14:22:44
【问题描述】:

我正在与一个可以返回以下 JSON 结构的 Web 服务交谈:

{
    "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。

【问题讨论】:

  • 你有没有在这里寻找想法:stackoverflow.com/a/18997172/226781
  • @asherber 是的,我已经看到了,这将是一个可能的解决方案,但它需要将我的模型中的所有属性更改为数组/列表并将属性全部放在它们上。不会比我目前的解决方法好多少。
  • 另一个可能相关的问题:Deserialize JSON when type can be different。但是,如果您说您必须为 所有可能的 属性(包括具有原始值的属性)执行此操作,那么接受的答案可能不起作用。
  • 或者,将您的 JSON 预加载到 JToken 并使用来自 Woo commerce json to Dataset or datatable 的 RemoveEmptyArrayProperties。
  • @dbc,RemoveEmptyArrayProperties 工作!谢谢。你会回答还是我应该创建一个社区 Wiki 答案?

标签: c# json json.net deserialization json-deserialization


【解决方案1】:

避免此问题的一种简单方法是将 JSON 预加载到 JToken 中,然后使用扩展方法 RemoveEmptyArrayProperties 从 this answer 删除所有空数组属性到 Woo commerce json to Dataset or datatable :

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多