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

我有来自服务器的多个学生姓名的响应


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

 }

希望你得到这个..


慕桂英3389331
浏览 92回答 1
1回答

繁华开满天机

通常我会建议在模型中反序列化你的对象,但由于该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){&nbsp; &nbsp; string error = jObj["RESPONSE"]["LINEERROR"].ToString();&nbsp; &nbsp; Console.WriteLine($"Error: {error}");&nbsp; &nbsp; // or throw an exception&nbsp; &nbsp; 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){&nbsp; &nbsp; // If the student property is an array, add all names to the list.&nbsp; &nbsp; var studentArray = students as JArray;&nbsp; &nbsp; studentNames.AddRange(studentArray.Select(s => s.ToString()));}else{&nbsp; &nbsp; // If student property is a string, add that to the list.&nbsp; &nbsp; studentNames.Add(students.ToString());}foreach (var student in studentNames){&nbsp; &nbsp; // Doing something with the names.&nbsp; &nbsp; Console.WriteLine(student);}
打开App,查看更多内容
随时随地看视频慕课网APP