我的Json结构的一部分是dynacmic数组,我想用Json.Net读取它。 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是数组,我想访问该数组中的每个项目。 我该怎么办?
答案 0 :(得分:0)
很难根据有些模糊的要求确切地知道你需要什么,但是这里有一些代码可以让你获得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;
...
}