亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 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 關注
  • 133 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號