使用C#访问JSON中的多个数组 [英] Accessing multiple arrays in JSON using C#

查看:582
本文介绍了使用C#访问JSON中的多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON看起来像这样:

My JSON looks like this:

    {"2013" : [
        { "date":"2013-01-09 12:00:00","height":0 },
        { "date":"2013-01-19 12:00:00","height":3 },
        { "date":"2013-01-29 12:00:00","height":2 }],
    "2012" : [
        { "date":"2012-02-09 12:00:00","height":0 },
        { "date":"2012-02-19 12:00:00","height":4 },
        { "date":"2012-02-29 12:00:00","height":2 }],
    "2011" : [
        { "date":"2011-03-09 12:00:00","height":3 },
        { "date":"2011-03-19 12:00:00","height":8 },
        { "date":"2011-03-29 12:00:00","height":2 }]
   }

我想做的是获取所有日期和高度,但是我每年只能使用以下代码来做到这一点:

What I am trying to do is get all of the dates and height, but I am only able to do it per year using this code:

    public class Report
    {
        public DateTime Date { get; set; }
        public int Height { get; set; }
    }

    JObject data = JObject.Parse(sr);
    var postTitles = from p in data["2013"]
                     select new Report
                     {
                         Date = DateTime.Parse((string)p["date"]),
                         Height = (int)p["height"]
                     };

我当时正在考虑使用for循环,但是尝试在data ["]内部进行变量操作是行不通的.我也在考虑做var postTitles + =语句,但也不允许这样做.关于我应该如何处理的任何想法?我正在使用JSON.NET,建议我每年上一堂课(即2013年,2012年和2011年),但我希望将它们放在一堂课下,以便更轻松地操作数据.

I was thinking of using a for loop but trying a variable inside data[" "] won't work. I was also thinking of doing var postTitles += statement but it is not allowed as well. Any ideas on how I should go about this? I am using JSON.NET and it is suggested that I do a class per year (i.e. 2013, 2012, 2011) but I want them under one class to make it easier to manipulate data.

推荐答案

我稍微扭转了一下Mark的烦恼,然后想到了:

I turned and twisted Mark's anwer somewhat and came up with this:

var postTitles = data.Children() // Select array container properties, like "2013"
        .SelectMany(x => x.First) // Select each subitem from every array
        .Select(r => // Create a report for each item
            new Report
                {
                    Date = DateTime.Parse((string)r["date"]),
                    Height = (int)r["height"]
                }
            );

希望内联注释可以充分解释其逻辑.

Hopefully the inline comments will explain the logic sufficiently.

这篇关于使用C#访问JSON中的多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆