调用基于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