2017-03-31 31 views
-1

我試圖訪問我向API進行身份驗證時返回的json字符串的特定字段。當我嘗試打印或操縱我收到的字符串時在C中訪問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 

字符串「內容」持有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" 
} 

我已經試過許多應用的例子,我已經看到了計算器,但似乎沒有工作

回答

1

的關鍵區分大小寫。所有你需要做的是改變

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

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

沒聽清楚不過我還是收到了錯誤。 'Console.WriteLine(token);' 說System.NullReferenceException:'對象引用未設置爲對象的實例。' – Teragon

0

該行應該讀

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