[英]Saving json array to c# class object
我必須將 json 字符串數組分配給 ac# 類。 我做了如下。 但我有一個例外
無法將當前 JSON 數組(例如 [1,2,3])反序列化為“LoggedInUserDetails”類型,因為該類型需要 JSON 對象(例如 {\\"name\\":\\"value\\"})才能正確反序列化。\\r \\n要修復此錯誤,請將 JSON 更改為 JSON 對象(例如 {\\"name\\":\\"value\\"})或將反序列化類型更改為數組或實現集合接口的類型(例如 ICollection、IList ) 像可以從 JSON 數組反序列化的 List。 還可以將 JsonArrayAttribute 添加到類型以強制它從 JSON 數組反序列化。\\r\\n路徑 '',第 1 行,位置 1。"}
public class LoggedInUserDetails
{
public string login_user_name
{
get; set;
}
public string login_user_id
{
get; set;
}
}
var GetResponse = await response2.Content.ReadAsStringAsync();
//"[{\"login_user_name\":\"Rahul\",\"login_user_id\":\"43\"}]"
LoggedInUserDetails obj = JsonConvert.DeserializeObject<LoggedInUserDetails>(GetResponse);
Variables.login_user_name = obj.login_user_name;
Variables.login_user_id= obj.login_user_id;
您應該deserialize
json字符串deserialize
IEnumerable集合或Array
。
var content = await response2.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<LoggedInUserDetails>>(content);
這是因為 '[]' 將其存儲為結果數組。 您應該能夠執行以下操作:
LoggedInUserDetails obj = JsonConvert.DeserializeObject<List<LoggedInUserDetails>>(GetResponse);
您嘗試將對象反序列化為列表的地方。 該列表將僅包含 1 個對象。
完整示例:
public class LoggedInUserDetails
{
public string login_user_name
{
get; set;
}
public string login_user_id
{
get; set;
}
}
var GetResponse = await response2.Content.ReadAsStringAsync();
//"[{\"login_user_name\":\"Rahul\",\"login_user_id\":\"43\"}]"
List<LoggedInUserDetails> obj = JsonConvert.DeserializeObject<List<LoggedInUserDetails>>(GetResponse);
Variables.login_user_name = obj[0].login_user_name;
Variables.login_user_id= obj[0].login_user_id;
這邊走:
LoggedInUserDetails obj = JsonConvert.DeserializeObject<LoggedInUserDetails[]>(GetResponse).FirstOrDefault() ?? throw new Exception("User not found.");
Variables.login_user_name = obj.login_user_name;
Variables.login_user_id = obj.login_user_id;
您的結果是一個包含 1 個對象的數組,因此您只需將其轉換為所需對象的數組並取第一個。
由於您使用的是數組,那么它應該反序列化數組以列出 public class Test { public string login_user_name {get; 設置;} 公共字符串 login_user_id { 獲取; 放;} }
string js = "[{\"login_user_name\":\"Rahul\",\"login_user_id\":\"43\"}]";
var result = JsonConvert.DeserializeObject<List<Test>>(js);
foreach(var ob in result)
{
Console.WriteLine(ob.login_user_name);
Console.WriteLine(ob.login_user_id);
}
輸出
Rahul
43
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.