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

时间:2019-03-26 08:59:00

标签: c# windows

我收到服务器关于多个学生姓名的回复

{"ENVELOPE":{"STUDENTLIST":{"STUDENT":["John","HHH"]}}}

或单个学生姓名

{"ENVELOPE":{"STUDENTLIST":{"STUDENT":"John"}}}

如果有错误

{"RESPONSE":{"LINEERROR":"Could not find Students"}}

从这些响应中,如果没有错误,我想要一组学生姓名,否则出现错误的字符串,即string []名称= {“ John”,“ HHH”}或string []名称= {“ John”}否则string error =“找不到学生”;

我尝试过

 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 个答案:

答案 0 :(得分:0)

通常,我建议在模型中deserialize使用对象,但是由于STUDENT属性有时是数组,有时是字符串,所以很麻烦。我建议您deserialize收到的实际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);
}