1 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
通常我會(huì)建議在模型中反序列化你的對(duì)象,但由于該STUDENT
屬性有時(shí)是一個(gè)數(shù)組,有時(shí)是一個(gè)字符串,不幸的是,這很麻煩。我建議反序列化您收到的實(shí)際 xml,因?yàn)槲蚁M?xml 模型更容易處理。
與此同時(shí),這將起作用:
string input = "{\"ENVELOPE\":{\"STUDENTLIST\":{\"STUDENT\":[\"John\",\"HHH\"]}}}";
// string input = "{\"ENVELOPE\":{\"STUDENTLIST\":{\"STUDENT\":\"John\"}}}";
// string input = "{\"RESPONSE\":{\"LINEERROR\":\"Could not find Students\"}}";
JObject jObj = JObject.Parse(input);
if (jObj["RESPONSE"] != null)
{
string error = jObj["RESPONSE"]["LINEERROR"].ToString();
Console.WriteLine($"Error: {error}");
// or throw an exception
return;
}
var studentNames = new List<string>();
// If there is no error, there should be a student property.
var students = jObj["ENVELOPE"]["STUDENTLIST"]["STUDENT"];
if (students is JArray)
{
// If the student property is an array, add all names to the list.
var studentArray = students as JArray;
studentNames.AddRange(studentArray.Select(s => s.ToString()));
}
else
{
// If student property is a string, add that to the list.
studentNames.Add(students.ToString());
}
foreach (var student in studentNames)
{
// Doing something with the names.
Console.WriteLine(student);
}
- 1 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報(bào)