0

I am getting the following nested Json objects from an API I am calling.

{"status":"success","data":{"valid_for":3600,"token":"access_token","expires":1123123123123}}

The PostResponse class is like below

public class PostResponse
{
    public string status { get; set; }
    public Data data { get; set; }
}

public class Data
{
    public int valid_for { get; set; }
    public string token { get; set; }
    public int expires { get; set; }
}

I get null for postResponse with this code.

using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
     Console.WriteLine(reader.ReadToEnd());
     postResponse = JsonConvert.DeserializeObject<PostResponse>(reader.ReadToEnd());
}
6
  • 5
    from your sample json: {"status":"success","data":"valid_for":3600,"token":"acces_token","expires":1123123123123}} is not a valid json, you missed { before "valid_for" Commented Mar 21, 2017 at 19:34
  • 3
    When you do a ReadToEnd don't you have to set the read pointer to the start of the stream again in order to make a new ReadToEnd, because if so when you try to parse the last ReadToEnd will return "". Commented Mar 21, 2017 at 19:34
  • @dcg Got it.That was the issue.Thanks. Commented Mar 21, 2017 at 19:36
  • you miss { just after "data": Commented Mar 21, 2017 at 19:36
  • 1
    jsonlint.com may help you in the future. Good luck! Commented Mar 21, 2017 at 19:36

1 Answer 1

1

You need to reset your stream pointer position, since you already read from a stream when you used WriteLine method.

Stream stream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
    Console.WriteLine(reader.ReadToEnd());

    stream.Position = 0; //Reset position pointer
    reader.DiscardBufferedData();

    postResponse = JsonConvert.DeserializeObject<PostResponse>(reader.ReadToEnd());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.