首页 > 解决方案 > 从 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");                    
 }

希望你得到这个..

标签: c#windows

解决方案


通常我会建议在模型中反序列化你的对象,但由于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);
}

推荐阅读