How to use System.Text.Json to write a Json object having a nested Json array?

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello,
Today, I upgrade my IDE from Visual Studio 2019 Version 16.3.0 to 16.3.1 on Windows 10 (Version 1903).
I want to try some new stuff, like System.text.json, if succeed, I can get rid of Newtonsoft.json.
I know how to write a simple Json Object with Utf8JsonWriter, but I have some data having nested Json array.
Like the following Json data:
{
"account_id": "1234567890",
"rate": 1.0,
"balance": ["GBP", 10000.0],
"account_open": true
}
For the json key/value: "balance": ["GBP", 10000.0], it is a Json array, but I have no idea on how to write this Json array using Utf8JsonWriter.
I have tried the following C# code:

using var stream = new MemoryStream();
using (var writer0 = new Utf8JsonWriter(stream, options))
{
writer0.WriteStartArray();
writer0.WriteString("GBP", "10000.0");
writer0.WriteEndArray();
}
string json0 = Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(json0);


But I got run time error:
Message=Cannot write a JSON property within an array or as the first JSON token. Current token type is 'StartArray'.
Any idea on how to do the job? I want to write the complete Json object including Json array inside.
Thanks,

Continue reading...
 
Back
Top