我正在尝试学习这个新的 system.io.pipelines,以及用于反序列化 json 的新 webapi 策略...
我编写了自己的 JsonConverter,但我无法找出从 json 平面文件固定装置初始化 Utf9JsonReader 的正确方法。
这是测试:
[Fact]
public void WhenGivenJsonObjectThenEntityDTOReturned() {
using(var stream = new FileStream("Fixtures/BookStoreJson.json", FileMode.Open))
{
var pipe = PipeReader.Create(stream);
ReadResult bytes;
pipe.TryRead(out bytes);
var reader = new Utf8JsonReader(bytes.Buffer);
var target = new EntityDTOConverter();
reader.Read();
var actual = target.Read(ref reader, typeof(EntityDTO), new JsonSerializerOptions());
Assert.True(actual.Props.ContainsKey("name"));
}
}
当我调试此问题时,bytes.buffer 设置为 0 字节,即使 BookStoreJson.json 文件包含以下内容:
{
"name": "Tattered Cover",
"store":{
"book":[
{
"category":"reference",
"author":"Nigel Rees",
"title":"Sayings of the Century",
"price":8.95
},
{
"category":"fiction",
"author":"Evelyn Waugh",
"title":"Sword of Honour",
"price":12.99
},
{
"category":"fiction",
"author":"J. R. R. Tolkien",
"title":"The Lord of the Rings",
"isbn":"0-395-19395-8",
"price":22.99
}
],
"bicycle":{
"color":"red",
"price":19.95
}
}
}
最佳答案
抱歉,我没有意识到异步过程,我正在从控制台应用程序进行测试。除了不确定这个答案会对您有多大帮助之外,基本上您可以通过访问结果来运行同步异步任务。缓冲区大小也有限制,如果 json 文件大小较大,您可能需要创建自定义池并使用 AdvanceTo 选项读取缓冲区末尾以获取流。
using System;
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
public class Person
{
public string Email { get; set; }
public bool Active { get; set; }
public string CreatedDate { get; set; }
public string[] Roles { get; set; }
}
[Fact]
public void WhenGivenJsonObjectThenEntityDTOReturned()
{
//{
// "Email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ce6ede1e9ffcce9f4ede1fce0e9a2efe3e1" rel="noreferrer noopener nofollow">[email protected]</a>",
// "Active": true,
// "CreatedDate": "2013-01-20T00: 00: 00Z",
// "Roles": [
// "User",
// "Admin"
// ]
//}
using (var stream = new FileStream(@"c:\temp\json.json", FileMode.Open))
{
var reader = PipeReader.Create(stream,
new StreamPipeReaderOptions(bufferSize:4096 *2));
ValueTask<ReadResult> readResult = reader.ReadAsync();
ReadOnlySequence<byte> buffer = readResult.Result.Buffer;
Assert.True(readResult.IsCompleted);
var jsonStreamReader = new Utf8JsonReader(buffer);
var expectedJson = JsonSerializer
.Deserialize<Person>(Encoding.UTF8.GetString(buffer.ToArray()));
Assert.Equal("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd979c90988ebd98859c908d9198d39e9290" rel="noreferrer noopener nofollow">[email protected]</a>", expectedJson.Email);
}
}
关于c# - 如何使用 PipeReader 读取 JSON 平面文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64602575/