简体   繁体   中英

Read/Write JSON using System.Text.Json

We are using NewtwonSoft.json currently but need to move to System.Text.JSON for security reasons.

So we are new to System.Text.JSON and are having trouble reading the following JSON file.

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. Prefer VB.net but googling has led us to believe VB.net is not supported much in System.Text.JSON. So C# will work. Appreciate any feed back that would get us going. We have tried using a practice C# Project but get error:

"System.Text.Json.JsonReaderException: ''0xEF' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0." at the line 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.

If the file contains a UTF-8 byte order mark, remove it before passing the bytes to the 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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