Search code examples
c#jsonjson-serialization

Serializing a nested json object into an opened Utf8JsonWriter


While serializing with Utf8JsonWriter, I want to add a field which is a complex object. I want to just serialize it like a nested json:

public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions options)
{
    writer.WriteStartObject();
    writer.WriteString("simpleField1", "value1");
    writer.WriteString("simpleField2", "value2");
    ....
    writer.WriteString("bar", JsonSerializer.Serialize(foo.Bar));
    ....
    writer.WriteEndObject();
    writer.Flush();
}

This results in any quotes being escaped to \u0022, however. How can I properly add an already serialized object while writing in Utf8JsonWriter?


Solution

  • Found the answer eventually, I just need to give the writer to the serializer:

    writer.WritePropertyName("bar");
    JsonSerializer.Serialize(writer, foo.Bar);
    

    This resulted exactly in what I need.