使用Json.Net反序列化嵌套的json对象返回null

时间:2017-03-21 19:31:49

标签: c# json json.net

我从我正在调用的API中获取以下嵌套的Json对象。

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

PostResponse类如下所示

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; }
}

我使用此代码获取postResponse的null。

using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
     Console.WriteLine(reader.ReadToEnd());
     postResponse = JsonConvert.DeserializeObject<PostResponse>(reader.ReadToEnd());
}

1 个答案:

答案 0 :(得分:1)

您需要重置流指针位置,因为您在使用WriteLine方法时已从流中读取。

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());
}