【问题标题】:Json children properties to dictionaryJson子属性到字典
【发布时间】:2015-03-18 10:55:18
【问题描述】:

我正在尝试为 JToken 上的所有子节点的属性提取日期列表,但无法正确获取语法。

我想获取属性 "timeStamp": "2013-09-11T00:30:00Z" 中的日期列表,以便确定所有子节点的最小/最大日期。

我尝试了以下方法,它返回一个匿名类型,并且很难使用返回的对象。

var timeStamps = Jarr.Select(x => new
{
   timeStamp = (DateTime)x.SelectToken("timeStamp")
});
  1. 我怎样才能只说所有子时间戳中的 List<string>List<DateTime>
  2. 是否可以得到Dictionary<string, DateTime>的id、时间戳?

Json 看起来像这样,所以基本上从 LEVEL1 我想检查所有孩子,孩子的孩子是否有相同的属性。

{
  "children": [
    {
      "type": "LEVEL2",
      "name": "Item1",
      "id": "1.7193",
      "timeStamp": "2013-09-11T00:30:00Z",
    },
    {
      "type": "LEVEL2",
      "name": "Item2",
      "id": "1.7194",
      "timeStamp": "2013-09-11T00:30:00Z",
    },
    {
      "type": "LEVEL2",
      "name": "Item3",
      "id": "1.7191",
      "timeStamp": "2013-09-11T00:30:00Z",
    }
  ],
  "type": "LEVEL1",
  "name": "Stock-FRT54443",
  "id": "1000145",
  "countryCode": "en"
}

和方法

    void AddNodes(TreeView treeView, JObject jObj, TreeNodeCollection parent)
    {
        JToken Jarr = null;
        Dictionary<string, string> marketProperties = new Dictionary<string, string>();
        foreach (var property in jObj.Properties())
        {
            if (property.Name == "children")
            {
                Jarr = property.Value;
            }
            else
            {
                string key = property.Name;
                string prop = property.Value.ToString();
                marketProperties.Add(key, prop);
            }

        }

        if (marketProperties["type"] == "LEVEL1")
        {
          //Not working!
          var timeStamps = Jarr["timeStamp"].Values<string>();
        }
    }

【问题讨论】:

    标签: c# json linq


    【解决方案1】:

    当您使用“new”关键字时,它将创建一个匿名类型。您正在创建具有时间戳属性的对象列表,而不是日期时间列表。获取日期列表所需要做的就是将其更改为:

    DateTime timeStamps = Jarr.Select(x => (DateTime)x.SelectToken("timeStamp")).ToList();
    

    也可以获取字典:

    Dict<string,DateTime> dictionary = Jarr["children"].ToDictionary(x=>x["Id"].ToString(),x=>(DateTime)(x["timeStamp"]));
    

    第二个未经测试,但应该给你一个大致的想法。

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多