2013-11-14 31 views
12

您好我有JSON,看起来像这样的JSON对象的值和键:获取使用Json.Net C#有

{ 
    "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 

回答

14

因此,这里是他的代码可以得到每个项目的键和值的对象数组中:

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

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