[英]Read dynamic json property values using JObject c#
Part of my Json structre is dynacmic array and i want to read it using Json.Net . 我的Json结构的一部分是动态数组,我想使用Json.Net读取它。 The json structre is json structre是
{
"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
}
} }
How can i access the set of preferences in my c# code . 我如何在我的C#代码中访问首选项集。 I gets the preference tag from json using the below code 我使用以下代码从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
}
Now i want to navigate to each preference items , store the name and value properties. 现在,我想导航到每个首选项,存储名称和值属性。 If Value is array i want to access each items in that array . 如果Value是array我想访问该数组中的每个项目。 How can i do it? 我该怎么做?
It's hard to know exactly what you need based on the somewhat vague requirements, but here's some code which will get you a Dictionary<string, JToken>
of the preferences: 根据一些模糊的要求很难确切地知道您需要什么,但是下面的一些代码将为您提供首选项的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
You can then do whatever you want with the tokens. 然后,您可以使用令牌进行任何操作。 Anything where the value itself is an array will have have a JArray
value. 该值本身是数组的任何东西都将具有JArray
值。 You can test that easily enough: 您可以轻松地进行测试:
JToken value = dictionary[key];
JArray array = value as JArray;
if (array != null)
{
...
}
Or: 要么:
JToken value = dictionary[key];
if (value.Type == JTokenType.Array)
{
JArray array = (JArray) value;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.