用空数组反序列化 JSON 对象

Deserialize JSON object with blank array

当存在 empty/null 属性(使用 JSON.NET)时,我在反序列化 JSON 对象时遇到了一些麻烦,希望有人能指出我正确的方向。下面是我正在尝试并在 dotnetfiddle

测试的代码片段

这是 JSON 的示例:

{
    "`LCA0009": [],
    "`LCA0001": {
        "23225007190002": "1",
        "23249206670003": "1",
        "01365100070018": "5"
    },
    "`LCA0003": {
        "23331406670018": "1",
        "24942506670004": "1"
    },
    "`LCA0005": {
        "01365100070018": "19"
    }
}

我正在尝试使用此代码:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {

        string json = "{\"`LCA0009\": [], \"`LCA0001\": {\"23225007190002\": \"1\",\"23249206670003\": \"1\",\"01365100070018\": \"5\"},\"`LCA0003\": {\"23331406670018\": \"1\",\"24942506670004\": \"1\"},\"`LCA0005\": {\"01365100070018\": \"19\"}}";
        Console.WriteLine(json);
        Console.WriteLine();

        Console.WriteLine("This works");
        var root = JsonConvert.DeserializeObject(json);
        Console.WriteLine(root);

        Console.WriteLine("This doesn't work");
        var root2 = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
        Console.WriteLine(root2);

        foreach (var locationKvp in root2)
        {
            foreach (var skuKvp in locationKvp.Value)
            {
                Console.WriteLine("location: " + locationKvp.Key + ", sku: " +  skuKvp.Key + ", qty: " + skuKvp.Value);
            }
        }
    }
}

上面的"doesn't work"是我得到这个错误:

Run-time exception (line 19): Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '`LCA0009', line 1, position 14.

如何删除具有 null/empty 数组的属性?

从根本上说,JSON 是不一致的,最好的答案是使其一致。谁给你 JSON 需要被告知修复它。

Until/unless 你可以这样做,你可以自己将 "raw" 版本转换为 Dictionary<string, Dictionary<string, int>>,但工作量更大:

https://dotnetfiddle.net/zdeOOX

string json = "{\"`LCA0009\": [], \"`LCA0001\": {\"23225007190002\": \"1\",\"23249206670003\": \"1\",\"01365100070018\": \"5\"},\"`LCA0003\": {\"23331406670018\": \"1\",\"24942506670004\": \"1\"},\"`LCA0005\": {\"01365100070018\": \"19\"}}";

// Convert it
var root = (JObject)JsonConvert.DeserializeObject(json);
var results = new Dictionary<string, Dictionary<string,int>>();
foreach (var entry in root)
{
    var dict = new Dictionary<string,int>();
    if (!(entry.Value is JArray))
    {
        foreach (var subentry in (JObject)entry.Value)
        {
            int v;
            if (int.TryParse(((JValue)subentry.Value).ToString(), out v))
            {
                dict.Add(subentry.Key, v);
            }
        }
    }
    results.Add(entry.Key, dict);
}

// Results:
foreach (var name in results.Keys)
{
    var entry = results[name];
    Console.WriteLine(name + ":");
    foreach (var entryKey in entry.Keys)
    {
        Console.WriteLine("- " + entryKey + ": " + entry[entryKey]);
    }
}

我希望使用 Linq 可以使它变得更加优雅。