使用Json.Net C#获取json对象中的值和键 [英] Get values and keys in json object using Json.Net C#

查看:1535
本文介绍了使用Json.Net C#获取json对象中的值和键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的json:

Hi there I have json that looks like this:

{
    "Id": " 357342524563456678",
    "title": "Person",
    "language": "eng",
    "questionAnswer": [
        {
            "4534538254745646.1": {
                "firstName": "Janet",
                "questionNumber": "1.1"
            }
        }
    ]
}

现在,我编写了一些代码,这些代码循环遍历questionAnswer数组中的对象,然后获取对象的名称,即4534538254745646.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.

我该怎么做,这是我的代码:

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

推荐答案

因此,这是他完整的代码,可获取数组对象中每个项目的键和值:

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

这篇关于使用Json.Net C#获取json对象中的值和键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆