1 回答

TA貢獻1816條經驗 獲得超4個贊
通常我會建議在模型中反序列化你的對象,但由于該STUDENT
屬性有時是一個數組,有時是一個字符串,不幸的是,這很麻煩。我建議反序列化您收到的實際 xml,因為我希望 xml 模型更容易處理。
與此同時,這將起作用:
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 關注
- 133 瀏覽
添加回答
舉報