使用JObject c#读取动态json属性值



我的Json结构的一部分是动态数组,我想使用Json读取它。网json结构是

{
"objects": [{
    "id": "521daea47288c7794c88c923",
    "name": "Rass",
    "email": "ras@hjsh.com",
    "username": "ras",
    "books": [],
    "devices": [],
    "preferences": [
    {
    "name": "key1",
    "value": [
      {
        "id": "val1Id",
        "params": [
          {
            "name": "set1key",
            "value": 0
          },
          {
            "name": "set1key2",
            "value": 0
          },
          {
            "name": "set1key3",
            "value": 0.5
          }
        ]
      },
      {
        "id": "val2Id",
        "params": [
          {
            "name": "set2key",
            "value": 0
          },
          {
            "name": "set2key2",
            "value": 0
          },
          {
            "name": "set2key3",
            "value": 0.5
          }
        ]
      }
    ]
  },
  {
    "name": "language",
    "value": "en_US"
  },
  {
    "name": "page_zoom",
    "value": 1
  }
],
"created": "2013-08-28T08:02:44.000Z"
}],
"meta": {
    "total_count": 1,
    "offset": 0,
    "limit": 1000
}

}

如何在我的c#代码中访问首选项集?使用下面的代码

从json中获取首选项标签
   var jObject = JObject.Parse(jsonString);
        JObject obj = (JObject)jObject["objects"][0]["preferences"][0];
        string pref = "";
        foreach (var pref_item in obj)
        {
            string key = pref_item.Key;               
           //Here i want to check the Value is of type array, then get each item from Array.
            //If its not an array simply read the value
        }

现在我想导航到每个首选项,存储名称和值属性。如果Value是array,我想访问该数组中的每个项。我该怎么做呢?

根据一些模糊的需求很难确切地知道您需要什么,但是这里的一些代码将为您提供首选项的Dictionary<string, JToken>:

JArray preferences = (JArray)jObject["objects"][0]["preferences"];
var dictionary = preferences.ToDictionary(x => (string) x["name"],
                                          x => x["value"]);
// For example...
Console.WriteLine(dictionary["language"]); // prints en_US

然后你可以对这些令牌做任何你想做的事情。任何值本身是数组的东西都有一个JArray值。您可以很容易地进行测试:

JToken value = dictionary[key];
JArray array = value as JArray;
if (array != null)
{
    ...
}    

或:

JToken value = dictionary[key];
if (value.Type == JTokenType.Array)
{
    JArray array = (JArray) value;
    ...
}

相关内容

  • 没有找到相关文章