c# - 从 C# 桌面应用程序中的 json 字符串响应中获取数据
问题描述
我有来自服务器的多个学生姓名的响应
{"ENVELOPE":{"STUDENTLIST":{"STUDENT":["John","HHH"]}}}
或单个学生姓名
{"ENVELOPE":{"STUDENTLIST":{"STUDENT":"John"}}}
如果有错误
{"RESPONSE":{"LINEERROR":"Could not find Students"}}
从这些回复中,如果没有错误,我想要学生姓名数组,否则有错误的字符串,即字符串 [] 名称 = {"John","HHH"} 或字符串 [] 名称 = {"John"} 否则字符串错误 = "找不到学生”;
我试过
JObject jObj = JObject.Parse(responseFromServer);
var msgProperty = jObj.Property("ENVELOPE");
var respProperty = jObj.Property("RESPONSE");
//check if property exists
if (msgProperty != null)
{
var mag = msgProperty.Value;
Console.WriteLine("has Student : " + mag);
/*
need logic here :/ */
}
else if (respProperty != null)
{
Console.WriteLine("no Students");
}
else
{
Console.WriteLine("Error while getting students");
}
希望你得到这个..
解决方案
通常我会建议在模型中反序列化你的对象,但由于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);
}
推荐阅读
- python - 尝试使预训练的 BERT 适应句子语义分离的另一个用例
- python - conda install packages 错误:收集包元数据(current_repodata.json):失败
- sql - 新手:将数据批量添加到 sqlite 数据库的最简单方法是什么?
- rust - 即使 src/main.rs 可用, cargo 也不会构建
- arrays - 使用父 ID 将平面 JSON 字符串转换为层次结构
- python - 使用 OpenCV Python 运行硬件优化的 NVIDIA 光流
- mongodb - 当localField为字符串且foreignField为ObjectId格式时的Mongodb $lookup
- java - 单击按钮时如何延迟程序(java swing)
- android-studio - 在颤振中使用 image_picker 时遇到错误
- python - 在 Python 中将命令与变量结合起来