Skip to content

Instantly share code, notes, and snippets.

@richlander
Created January 29, 2019 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richlander/4c1377ebec06aa0526c086843bdae946 to your computer and use it in GitHub Desktop.
Save richlander/4c1377ebec06aa0526c086843bdae946 to your computer and use it in GitHub Desktop.
Sample usage of Utf8JsonWriter
static int WriteJson(IBufferWriter<byte> output, long[] extraData)
{
var json = new Utf8JsonWriter(output, state: default);
json.WriteStartObject();
json.WriteNumber("age", 15, escape: false);
json.WriteString("date", DateTime.Now);
json.WriteString("first", "John");
json.WriteString("last", "Smith");
json.WriteStartArray("phoneNumbers", escape: false);
json.WriteStringValue("425-000-1212", escape: false);
json.WriteStringValue("425-000-1213");
json.WriteEndArray();
json.WriteStartObject("address");
json.WriteString("street", "1 Microsoft Way");
json.WriteString("city", "Redmond");
json.WriteNumber("zip", 98052);
json.WriteEndObject();
json.WriteStartArray("ExtraArray");
for (var i = 0; i < extraData.Length; i++)
{
json.WriteNumberValue(extraData[i]);
}
json.WriteEndArray();
json.WriteEndObject();
json.Flush(isFinalBlock: true);
return (int)json.BytesWritten;
}
@dazinator
Copy link

dazinator commented Oct 24, 2019

How to you write values that you are reading from a Utf8JsonReader? I'm looking for something like json.WriteValue(jsonReader.ValueSpan)

@humbertropolis
Copy link

Thank you so much, it was very helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment