我正在获取JSON格式的API响应,如下所示:
{
"token_type":"Bearer",
"access_token":"12345678910",
"user":{
"id":123456,
"username":"jbloggs",
"resource":2,
"firstname":"joe"
}
}
dynamic usrdetail = JsonConvert.DeserializeObject(JSONString);
我可以使用usrdetail来访问token_type和access_token(usrdetail.access_token),但是如何获取用户信息?
我尝试了usrdetail.user.id,但这不起作用?
谢谢 G
答案 0 :(得分:2)
1)从json2csharp
public class User
{
public int id { get; set; }
public string username { get; set; }
public int resource { get; set; }
public string firstname { get; set; }
}
public class Token
{
public string token_type { get; set; }
public string access_token { get; set; }
public User user { get; set; }
}
2)然后将您的json反序列化为上述快速类型,例如
class Program
{
static void Main(string[] args)
{
string json = @"{ 'token_type':'Bearer','access_token':'12345678910','user':{
'id':123456,'username':'jbloggs','resource':2,'firstname':'joe'}
}";
Token token = JsonConvert.DeserializeObject<Token>(json);
Console.WriteLine("token_type: " + token.token_type);
Console.WriteLine("access_token: " + token.access_token);
Console.WriteLine();
Console.WriteLine("id: " + token.user.id);
Console.WriteLine("username: " + token.user.username);
Console.WriteLine("resource: " + token.user.resource);
Console.WriteLine("firstname: " + token.user.firstname);
Console.ReadLine();
}
}
输出:
答案 1 :(得分:1)
JSON对象以键/值对形式编写。因此,要访问JSON对象,您可以使用方括号并将密钥放在其中。
因此,在您的示例中,您可以执行usrdetail["user"]["id"]
,该操作应检索用户的ID。
答案 2 :(得分:1)
这应该有效。
var jsonStr = "{ \"token_type\":\"Bearer\",\"access_token\":\"12345678910\",\"user\":{\"id\":123456,\"username\":\"jbloggs\",\"resource\":2,\"firstname\":\"joe\"}}";
dynamic jsonObject = JsonConvert.DeserializeObject(jsonStr);
int userId = jsonObject.user.id;
Console.WriteLine(userId);
查看此内容:https://github.com/cajomferro/basic-cmake/blob/master/myapp-avr/CMakeLists.txt
答案 3 :(得分:0)
您可以序列化动态对象dynamic usrdetail
,然后将其反序列化为如下所示的预定义对象:
dynamic usrdetail = JsonConvert.DeserializeObject(JSONString);
var jsonParam = JsonConvert.SerializeObject(usrdetail);
PredefiendClass obj = JsonConvert.DeserializeObject<PredefiendClass>(jsonParam);