Skip to content

Instantly share code, notes, and snippets.

@OskarKlintrot
Last active August 11, 2024 14:15
Show Gist options
  • Save OskarKlintrot/97685987fb3f12c00b25f1001378401c to your computer and use it in GitHub Desktop.
Save OskarKlintrot/97685987fb3f12c00b25f1001378401c to your computer and use it in GitHub Desktop.
Write to Utf8JsonWriter from Utf8JsonReader
var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json));
using var stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream))
{
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.None:
break;
case JsonTokenType.StartObject:
writer.WriteStartObject();
break;
case JsonTokenType.EndObject:
writer.WriteEndObject();
break;
case JsonTokenType.StartArray:
writer.WriteStartArray();
break;
case JsonTokenType.EndArray:
writer.WriteEndArray();
break;
case JsonTokenType.PropertyName:
if (reader.GetString() is string key)
{
writer.WritePropertyName(key);
}
else
{
throw new InvalidOperationException("Property name is not a string. This is most likely a programming error.");
}
break;
case JsonTokenType.Comment:
writer.WriteCommentValue(reader.GetComment());
break;
case JsonTokenType.String:
// If it's English-only:
writer.WriteStringValue(reader.ValueSpan);
// Works for åäö at least:
writer.WriteStringValue(Encoding.UTF8.GetBytes(reader.GetString() ?? string.Empty));
break;
case JsonTokenType.Number:
case JsonTokenType.True:
case JsonTokenType.False:
case JsonTokenType.Null:
writer.WriteRawValue(reader.ValueSpan);
break;
default:
throw new NotImplementedException($"Havn't implemented {reader.TokenType} yet.");
}
}
}
var copiedJson = Encoding.UTF8.GetString(stream.ToArray());
@AdamKlob
Copy link

writer.WriteStringValue(Encoding.UTF8.GetBytes(reader.GetString() ?? string.Empty)); makes double escape on , so \n becomes \n and so on.

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