調用基於REST的API會返回JSON格式的數據(存儲在變量strJSONStringFromAPI中)。Newtonsoft.Json:無法獲取JSON數據以轉換爲C#對象
{
"id": "551",
"name": "Dev D",
"work": [
{
"employer": {
"name": "Microsoft Corporation"
},
"position": {
"name": "Software Development"
}
}
],
"gender": "male"}
我已經創建以下對應於上述JSON數據
public class Employer
{
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
public class Position
{
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
public class Work
{
private Employer _employer;
private Position _position;
public Employer employer
{
get { return _employer; }
set { _employer = value; }
}
public Position position
{
get { return _position; }
set { _position = value; }
}
}
public class UserInfo
{
private string _id;
private string _name;
private Work[] _wk;
public string id
{
get { return _id; }
set { _id = value; }
}
public string name
{
get { return _name; }
set { _name = value; }
}
public Work[] work
{
get { return _wk; }
set { _wk = value; }
}
}
現在類我有方法GetUserInfo應返回對象的UserInfo如下所示
Public UserInfo GetUserDetails()
{
UserInfo user = New UserInfo();
user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(strJSONStringFromAPI);
return user;
}
以後我將訪問的值as
label1.text = user.ID ;
label2.text = user.name;
截至目前,我正在將上述用戶對象的所有屬性設置爲NULL(user.ID = null等等) 我知道我錯過了一些非常重要的東西在這裏..有人可以幫助我還有什麼需要在僱主中完成,職位和工作類,以便我得到適當的值(例如user.ID =「551」等)
oops..that是typo..fixed它 – NoobDeveloper
是啊,如果我將屬性聲明爲public string id {get;設置;}等然後它的工作..但如果我設置它的舊式的方式..(聲明私有變量_id和返回它)它不會工作。 – NoobDeveloper
適合我的任何一種方式......我會期待儘可能多的,並複製/粘貼上面更正的代碼片段來驗證。 – kuujinbo