在C#中访问JSON字符串的字段

时间:2017-03-31 20:02:39

标签: c# json

我正在尝试访问在向API进行身份验证时返回的json字符串的特定字段。当我尝试打印或操纵我收到的字符串时

System.NullReferenceException:'对象引用未设置为对象的实例。'

var response = client.GetAsync(fullUri).Result;
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("StatusCode : " + (int)response.StatusCode + " " + response.StatusCode.ToString());

var jo = JObject.Parse(content);
var token = jo["Result"]["Token"].ToString(); //error mentioned above received here
Console.WriteLine(token.ToString());          //error mentioned above also recieved here
Console.WriteLine(content);                   //error mentioned above received here too

字符串“content”使json看起来像这样:

{
    "Result":{
        "TenantId":"1",
        "Token":"38255507",
        "UserName":"kadmin",
        "RoleId":2,
        "ScopeId":"2",
        "AdminId":16596942,
        "MachineId":null,
        "MachineGroupName":null,
        "CultureInfo":"en-US",
        "TimePref":"Browser",
        "OffSetInMinutes":420,
        "Attributes":null
    },
    "ResponseCode":0,
    "Status":"OK",
    "Error":"None"
}

我已尝试应用我在stackoverflow上看到的许多示例但似乎没有工作

2 个答案:

答案 0 :(得分:1)

密钥区分大小写。您需要做的就是改变

var token = jo["result"]["Token"].ToString();

var token = jo["Result"]["Token"].ToString();

答案 1 :(得分:0)

该行应为

var token = jo["Result"]["Token"].ToString();