StreamReader 返回 null
StreamReader returning null
我的目标是开始使用 Stream
来读取 HTTP 内容 (HttpResponseMessage.Content
)。至于目前我正在使用 ReadAsStringAsync
阅读内容,我想通过 ReadAsStreamAsync
.
提高性能和内存使用率
为了实现这一点,我构建了一个小型单元测试,它应该安排一个 Stream,然后读取它并将其转换为原始对象。
预期的结果应该是反序列化后的原始对象,但是returns null。
// Arrenge
List<TypiCode> typiCodes = new List<TypiCode>()
{
new TypiCode()
{
Completed = true,
Id = this._random.Next(1000),
Title = Guid.NewGuid().ToString(),
UserId = this._random.Next(1000)
}
};
var jsonSerializer = new JsonSerializer();
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();
// Act
List<TypiCode> result = null;
using (var streamReader = new StreamReader(stream))
{
using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
{
result = jsonSerializer.Deserialize<List<TypiCode>>(jsonTextReader);
}
}
//Assert
Assert.IsNotNull(result); --> Failed!
型号:
[Serializable]
public class TypiCode
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public bool Completed { get; set; }
}
为什么 StreamReader 返回 null?
写入流后,您落后于数据。您需要重新开始。
重置流位置:
// your code
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
// more of youre code
独库:
我的目标是开始使用 Stream
来读取 HTTP 内容 (HttpResponseMessage.Content
)。至于目前我正在使用 ReadAsStringAsync
阅读内容,我想通过 ReadAsStreamAsync
.
为了实现这一点,我构建了一个小型单元测试,它应该安排一个 Stream,然后读取它并将其转换为原始对象。
预期的结果应该是反序列化后的原始对象,但是returns null。
// Arrenge
List<TypiCode> typiCodes = new List<TypiCode>()
{
new TypiCode()
{
Completed = true,
Id = this._random.Next(1000),
Title = Guid.NewGuid().ToString(),
UserId = this._random.Next(1000)
}
};
var jsonSerializer = new JsonSerializer();
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();
// Act
List<TypiCode> result = null;
using (var streamReader = new StreamReader(stream))
{
using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
{
result = jsonSerializer.Deserialize<List<TypiCode>>(jsonTextReader);
}
}
//Assert
Assert.IsNotNull(result); --> Failed!
型号:
[Serializable]
public class TypiCode
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public bool Completed { get; set; }
}
为什么 StreamReader 返回 null?
写入流后,您落后于数据。您需要重新开始。
重置流位置:
// your code
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
// more of youre code
独库: