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 关注
- 115 浏览
添加回答
举报