获取数组的名称

时间:2017-07-23 17:45:44

标签: c# json linq json.net

我有以下Json:

{
    "last_ts": "20161001154251",
    "first_ts": "20061130072151",
    "years": {
        "2006": [
            0,0,0,2,0,0,0,0,0,0,1,0
        ],
        "2007": [
            0,0,3,0,0,1,0,0,0,0,1,0
        ],
        "2008": [.........],
        .
        .
        .
    }
}

我想阅读每年的名字及其相应的数字数组,我尝试了以下代码:

JObject jObj = JObject.Parse(json);

var yearsA = jObj["years"];
foreach (var year in yearsA)
{
    string yearStr = year. // code here to retrieve this year's name
    foreach (var month in year.Children<JArray>().Children()) // loop thru each array value
    {
        int m = (int)month;
        if(m > 0)
        {
            years.Add(yearStr);
            break;
        }
    }
} 

我现在想要的只是一种获取阵列名称的方法,我尝试了很多解决方案,但没有一个适用于我。

3 个答案:

答案 0 :(得分:1)

只需声明一个类

public  class MyObj
{
    public string last_ts { set; get; }
    public string first_ts { set; get; }
    public Dictionary<int,int[]> years { set; get; }
}

并反序列化为

var data = JsonConvert.DeserializeObject<MyObj>(jsonString);

样本用法:

foreach(var entry in data.years)
{
    int year = entry.Key;
    int[] months = entry.Value.Where(m => m > 0).ToArray();
    Console.WriteLine(year + " => " + string.Join(",", months));
}

答案 1 :(得分:1)

试试这段代码:

var yearsA = jObj["years"].Cast<JProperty>();
List<string> years = new List<string>();
foreach (var year in yearsA)
{
    foreach (var month in year.Children<JArray>().Children()) // loop thru each array value
    {
        int m = (int) month;
        if (m > 0)
        {
            years.Add(year.Name);
            break;
        }

    }
}

答案 2 :(得分:0)

如果您想使用Linq to JSON,您可以执行类似的操作,但还有很多其他选项,如另一个答案所述。

 string json = @"{
            'last_ts': '20161001154251',
            'first_ts': '20061130072151',
            'years': {
                '2006': [
                    0,0,0,2,0,0,0,0,0,0,1,0
                ],
                '2007': [
                    0,0,3,0,0,1,0,0,0,0,1,0
                ],
            }
        }";

        JObject jObj = JObject.Parse(json);
        // since in your case your years and months are structure as key/value, it's possible to use built in class like Dictionary<TKey, TValue>
        var years = jObj["years"].ToObject<Dictionary<string, List<int>>>();

        var result = new Dictionary<string, List<int>>();

        foreach (var year in years)
        {
            string key = year.Key;
            var value = year.Value;
            var months = new List<int>();

            value.ForEach(t =>
            {
                if (t > 0)
                {
                    months.Add(t);
                }
            });

            result.Add(key, months);
        }

查看Convert JObject into Dictionary. Is it possible?

How do I get the list of keys in a dictionary?