19

您好,我的 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
4

1 回答 1

23

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

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

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

于 2013-11-14T10:43:04.867 回答