V
V
Vimake2014-02-04 21:44:52
C++ / C#
Vimake, 2014-02-04 21:44:52

Error while working with json.net

Here is my code

JObject test = JObject.Parse(auth_id);
             string access_token = (string)test["access_token"][1].ToString();
             textBox2.Text = access_token;

In auth_id
{"access_token":"0533","expires_in":0,"user_id":1}
What is wrong. Error in the third line
The error was of the form: check the value for null
I tried to fix it like this. The error is gone, but now all the data is empty. What to do?
string error = "";
     string user_id = "";
     string access_token = "";
     access_token = ((string)test["access_token"]) == null ? access_token : "";
     user_id = ((string)test["user_id"]) == null ? user_id : "";
     error = ((string)test["error"]) == null ? error : "";

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikolai Turnaviotov, 2014-02-04
@foxmuldercp

Are you trying to write web api client and store access token?

static async Task GetToken()
        {
            var client = new HttpClient();
            var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("grant_type", "password"), //AUTH TYPE, not a valid user pass
                new KeyValuePair<string, string>("username", "username"), // username
                new KeyValuePair<string, string>("password", "userpass") //current valid user password
            };
            var content = new FormUrlEncodedContent(pairs);

            var response = client.PostAsync("http://localhost:12437/Token", content).Result;

            if (response.IsSuccessStatusCode)
            {
                StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result);
                string json = reader.ReadLine();
               Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                var tokensavefile = File.CreateText(@"/path/to/save/token");
                string at = "";
                values.TryGetValue("access_token", out at);
                tokensavefile.WriteLine(at);
                r.Close();
                //File.Encrypt(@"/path/to/save/token");
            }
        }

Well, how to use this garbage:
static async Task GetVal()
        {
           var client = new HttpClient();
            List<string> bearer = File.ReadLines(@"/path/to/file/with/token").ToList();
            client.DefaultRequestHeaders.Add("Authorization", "bearer " + bearer.First());
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
           var response = client.GetAsync("http://localhost:12437/authorized/api/").Result; //b4a77b8d-bf41-e311-95b4-00248cc66523
 if (response.IsSuccessStatusCode)
            {
// Ну и понесся парсинг json'а.
// я вот сейчас воюю как раз - не стандартный обьект Json десериализовать
             }
else
{
// код возврата (не 200 ок), всё такое, развлекаемся с определением "почему не работает"
}

M
Mykola Dzedzinskyi, 2014-02-04
@dzedzinskiy

auth_id is json format string? If so, please name it correctly. Perhaps the string format does not match json, as a result, JObject.Parse could not parse the string, as a result, the access_token string will not exist. will be null , because there is no "access_token" element in test , and calling the ToStirng() method will throw an exception for the reason that the string must not be null.
Is it hard to debug code?

A
Alexey Gorshkov, 2014-02-18
@agorshkov23

why JObject test ... ?
use dynamic test...
thus you can simply do:

dynamic test = JObject.Parse(@"{"access_token":"0533","expires_in":0,"user_id":1}");
var accessToken = test.access_token.ToString ();
var expiresIn = int.ParseInt (test.expires_in.ToString ());
var userId = int.ParseInt (test.user_id.ToString ());

Just check variables then for null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question