简体   繁体   English

使用 System.Text.Json 读/写 JSON

[英]Read/Write JSON using System.Text.Json

We are using NewtwonSoft.json currently but need to move to System.Text.JSON for security reasons.我们目前正在使用 NewtwonSoft.json 但出于安全原因需要移至 System.Text.JSON。

So we are new to System.Text.JSON and are having trouble reading the following JSON file.因此,我们是 System.Text.JSON 的新手,并且无法读取以下 JSON 文件。

Ideally we would like to read and eventually put each record in a separate row in a Grid with the ID, Name and ContractTypeID as Columns A, B and C.理想情况下,我们希望读取并最终将每条记录放在 Grid 中的单独行中,ID、Name 和 ContractTypeID 作为列 A、B 和 C。 Prefer VB.net but googling has led us to believe VB.net is not supported much in System.Text.JSON.更喜欢 VB.net 但谷歌搜索让我们相信 VB.net 在 System.Text.JSON 中不受太多支持。 So C# will work.所以 C# 会起作用。 Appreciate any feed back that would get us going.感谢任何可以让我们继续前进的反馈。 We have tried using a practice C# Project but get error:我们尝试使用实践 C# 项目但得到错误:

"System.Text.Json.JsonReaderException: ''0xEF' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0." “System.Text.Json.JsonReaderException:''0xEF' 是值的无效开始。LineNumber:0 | BytePositionInLine:0。” at the line Reader.Read.在 Reader.Read 行。

var fileName = @"D:\MyFile.json";

byte[] data = System.IO.File.ReadAllBytes(fileName);

Utf8JsonReader reader = new Utf8JsonReader(data);

while (reader.Read())
[
    {
         "ID": "001",
         "Name": "INT SYS CO",
         "ContractTypeID": "CPAF"
    },
    {
         "ID": "002",
         "Name": "PLT",
         "ContractTypeID": "CPFF"
    },
    {
         "ID": "003",
         "Name": "SBAND",
         "ContractTypeID": "CPIF"
    },
    {
         "ID": "004",
         "Name": "SE",
         "ContractTypeID": "CPIF_PI"
    },
    {
         "ID": "005",
         "Name": "SPE",
         "ContractTypeID": "FFP"
    }
]

Obviously, the file is saved in UTF-8 encoding with BOM.很明显,文件是用 BOM 的 UTF-8 编码保存的。

If the file contains a UTF-8 byte order mark, remove it before passing the bytes to the Utf8JsonReader.如果文件包含 UTF-8 字节顺序标记,请在将字节传递给 Utf8JsonReader 之前将其删除。

ReadOnlySpan<byte> data = File.ReadAllBytes(fileName);

ReadOnlySpan<byte> utf8Bom = new byte[] { 0xEF, 0xBB, 0xBF };

if (data.StartsWith(utf8Bom))
{
    data = data.Slice(utf8Bom.Length);
}

Utf8JsonReader reader = new Utf8JsonReader(data);

See more in the documentation .文档中查看更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM