我正在尝试解析多级json数组,但是我得到以下异常:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Tractor.Models.UserDetails' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
以下是json的回复:
{
"status": 1,
"message": null,
"userdetails": [
{
"ID": 9,
"Name": "aleem",
"Company_Name": null,
"Email": null,
"Password": null,
"Created_Date": null,
"Email_Confirm": null,
"Token": null,
"Phone": null,
"Website": null,
"allcompanies": [
{
"Name": "self",
"allprojects": [
{
"ID": 1,
"Name": "test"
}
]
}
],
"screens": 3
}
]
}
以下是我为获取JSON响应而添加的类:
class LoginApiResponse
{
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("userdetails")]
public UserDetails UserDetails { get; set; }
}
class UserDetails
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Company_Name")]
public string Company_Name { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
[JsonProperty("Created_Date")]
public string Created_Date { get; set; }
[JsonProperty("Email_Confirm")]
public string Email_Confirm { get; set; }
[JsonProperty("Token")]
public string Token { get; set; }
[JsonProperty("Phone")]
public string Phone { get; set; }
[JsonProperty("Website")]
public string Website { get; set; }
[JsonProperty("allcompanies")]
public List<Company> Companies { get; set; }
[JsonProperty("screens")]
public int Screens { get; set; }
}
class Company
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("allprojects")]
public List<Project> Projects {get;set;}
}
class Project
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
我使用以下代码序列化此JSON:
var response = client.Execute(request);
var final = JsonConvert.DeserializeObject<LoginApiResponse>(response.Content);
答案 0 :(得分:1)
JSON要求UserDetails
字段是UserDetails
个对象的数组(或列表):
class LoginApiResponse
{
//.........
[JsonProperty("userdetails")]
public UserDetails[] UserDetails { get; set; }
// ^^
// Alternatively, use List<UserDetails> instead of UserDetails[]
}
答案 1 :(得分:0)
您的问题出在OnResume()
班。
属性OnCreate()
应为LoginApiResponse
,而不是UserDetails
。所以你得到:
List<UserDetails>
这是因为您期望UserDetails
的JSON中的数组/列表:
class LoginApiResponse
{
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("userdetails")]
public List<UserDetails> UserDetails { get; set; }
}
或者(如果您不期望用户详细信息列表),您也可以更改json(从列表到对象):
userdetails
答案 2 :(得分:-1)
我这样做的方法是将JSON对象反序列化为动态变量,然后访问该动态变量所需的属性,如果您愿意,可以使用它们初始化模型。