получить данные из строкового ответа json в настольном приложении c # - PullRequest
0 голосов
/ 26 марта 2019

У меня есть ответ от сервера как для имени нескольких учеников

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

или для имени одного ученика

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

, и если есть ошибка

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

Из этих ответов я хочу получить массив имен студентов, если нет ошибки, иначе строка с ошибкой, т.е. строка [] names = {"John", "HHH"} или string [] names = {"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 голосов
/ 26 марта 2019

Обычно я бы рекомендовал десериализовать ваш объект в модели, но поскольку свойство 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...