Json children属性到字典

时间:2015-03-18 10:55:19

标签: c# json linq

我正在尝试为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,timestamp?
  3. 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>();
            }
        }
    

1 个答案:

答案 0 :(得分:2)

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

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"]));

第二种是未经测试但应该给你一般的想法。

相关问题