-
Couldn't load subscription status.
- Fork 5.2k
Description
Background and motivation
Today there is no quick way to create a JsonElement instance from a JSON string. The nearest alternative is using the JsonDocument.Parse method:
JsonElement element = JsonDocument.Parse("{}").RootElement;However this approach has the disadvantage of creating an IDisposable JsonDocument which uses pooled buffers. The correct way to do this involves using the JsonElement.ParseValue(ref Utf8JsonReader) method as follows:
Utf8JsonReader reader = new("{}"u8);
JsonElement element = JsonElement.ParseValue(ref reader);or using JsonSerializer.Deserialize, which suffers from the usual suite of concerns when needing to write AOT friendly components:
JsonSerializer.Deserialize<JsonElement>("{}");This issue proposes we expose a couple of accelerator Parse methods on JsonElement that support creating non-pooled JsonElement instances.
API Proposal
namespace System.Text.Json;
public partial struct JsonElement
{
// Existing API
public static JsonElement ParseValue(ref Utf8JsonReader reader);
// New APIs
public static JsonElement Parse(string json);
public static JsonElement Parse(ReadOnlySpan<byte> utf8Json);
}API Usage
JsonElement element = JsonElement.Parse("{}"u8);Alternative Designs
No response
Risks
No response