使用 Json.Net C# 获取 json 对象中的值和键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19974763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get values and keys in json object using Json.Net C#
提问by Mike Barnes
Hi there I have json that looks like this:
嗨,我有一个看起来像这样的 json:
{
"Id": " 357342524563456678",
"title": "Person",
"language": "eng",
"questionAnswer": [
{
"4534538254745646.1": {
"firstName": "Janet",
"questionNumber": "1.1"
}
}
]
}
Now I have written some code that loops over the objects in the questionAnswer
array and then gets the name of the object which is 4534538254745646.1
. Now Im trying to save the key of each Item and the value aswell but I am only managing to get the value.
现在我已经编写了一些代码来遍历questionAnswer
数组中的对象,然后获取对象的名称,即4534538254745646.1
. 现在我试图保存每个项目的键和值,但我只能设法获取值。
How would I do this, here is my code:
我该怎么做,这是我的代码:
JToken entireJson = JToken.Parse(json);
JArray inner = entireJson["questionAnswer"].Value<JArray>();
foreach(var item in inner)
{
JProperty questionAnswerDetails = item.First.Value<JProperty>();
//This line gets the name, which is fine
var questionAnswerSchemaReference = questionAnswerDetails.Name;
var properties = questionAnswerDetails.Value.First;
//This only gets Janet
var key = properties.First;
var value = properties.Last;
}
So at the moment Im only able to get Janet, But I also want the firstname field. I want to then take this and add to a dictionary i.e.
所以目前我只能得到珍妮特,但我也想要名字字段。然后我想把它添加到字典中,即
Dictionary<string, string> details = new Dictionary<string, string>();
//suedo
foreach(var item in questionAnswerObjects)
details.Add(firstName, Janet);
//And then any other things found below this
采纳答案by Mike Barnes
So Here is he complete code that gets the keys and values for each item in the object in the array:
所以这是他获取数组中对象中每个项目的键和值的完整代码:
string key = null;
string value = null;
foreach(var item in inner)
{
JProperty questionAnswerDetails = item.First.Value<JProperty>();
var questionAnswerSchemaReference = questionAnswerDetails.Name;
var propertyList = (JObject)item[questionAnswerSchemaReference];
questionDetails = new Dictionary<string, object>();
foreach (var property in propertyList)
{
key = property.Key;
value = property.Value.ToString();
}
questionDetails.Add(key, value);
}
I can now add key and value to the dictionary
我现在可以将键和值添加到字典中