使用Json.Net C#获取json对象中的值和键

时间:2013-11-14 10:06:04

标签: c# json json.net

你好我有json,看起来像这样:

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

现在我编写了一些循环遍历questionAnswer数组中对象的代码,然后获取对象的名称4534538254745646.1。现在我试图保存每个项目的关键值以及价值,但我只是设法获得价值。

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

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;                                      
}

所以目前我只能得到珍妮特,但我也想要名字字段。我想接下来并加入字典,即

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

1 个答案:

答案 0 :(得分:16)

所以这是他完整的代码,它获取数组中对象中每个项的键和值:

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);               
}

我现在可以在字典中添加键和值