为了账号安全,请及时绑定邮箱和手机立即绑定

从 C# 桌面应用程序中的 json 字符串响应中获取数据

从 C# 桌面应用程序中的 json 字符串响应中获取数据

C#
慕桂英3389331 2022-11-13 14:43:29
我有来自服务器的多个学生姓名的响应{"ENVELOPE":{"STUDENTLIST":{"STUDENT":["John","HHH"]}}}或单个学生姓名{"ENVELOPE":{"STUDENTLIST":{"STUDENT":"John"}}}如果有错误{"RESPONSE":{"LINEERROR":"Could not find Students"}}从这些回复中,如果没有错误,我想要学生姓名数组 else string with error ie string[] names = {"John","HHH"} or string[] names = {"John"} else string error = "Could not find学生”;我试过 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");                     }希望你得到这个..
查看完整描述

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

}


查看完整回答
反对 回复 2022-11-13
  • 1 回答
  • 0 关注
  • 89 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信