Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a string array with a Utf8JsonWriter?

I am doing some tests and would like to manually write a JSON object to file using the Utf8JsonWriter rather than the JsonSerializer.

I have the following code:

writer.WriteStartObject();
writer.WriteStartObject("InformationObject");
writer.WriteString("Name", "Info Name");
writer.WriteString("Details", "Info Details");
writer.WriteStartArray("Tags");

In the Tags array property I would like to write an array of strings, however if I try to use WriteString or any other method after the WriteStartArray call, the code fails at runtime.

There is no "WriteArrayContents" method or anything like that, so I am curious what method you're meant to call after WriteStartArray to actually write the array contents?

Am I just misunderstanding the way JSON works or is there something I've missed with the MS API?

like image 273
Zintom Avatar asked Sep 15 '25 05:09

Zintom


1 Answers

You need to call WriteStringValue() to write a string value into an array:

Writes a string text value (as a JSON string) as an element of a JSON array.

And, more generally, you need to use one of the Write*Value() methods of Utf8JsonWriter (such as WriteBooleanValue() or WriteNumberValue()) to write an array element of the appropriate type.

Thus your Write() method should look like:

public override void Write(Utf8JsonWriter writer, InformationObject value, JsonSerializerOptions options)
{
    writer.WriteStartObject();
    writer.WriteStartObject("InformationObject");
    writer.WriteString("Name", "Info Name");
    writer.WriteString("Details", "Info Details");
    writer.WriteStartArray("Tags");     

    // Write some dummy values here
    writer.WriteStringValue("value1");
    writer.WriteStringValue("value2");

    writer.WriteEndArray();
    writer.WriteEndObject();
    writer.WriteEndObject();
}

Demo fiddle here.

like image 107
dbc Avatar answered Sep 17 '25 19:09

dbc