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



嗨,我有如下所示的 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

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

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

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

相关内容

  • 没有找到相关文章

最新更新