Skip to content

Workaround for providing support for types JObject with System.Text.Json #82180

Discussion options

You must be logged in to vote

Here's an example implementation of a JsonConverter that can be used to serialize and deserialize JToken objects using the System.Text.Json library:

public class JTokenConverter : JsonConverter<JToken>
{
    public override bool CanConvert(Type typeToConvert) => typeof(JToken).IsAssignableFrom(typeToConvert);
    public override JToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // Use JsonDocument to parse the JSON and create a JToken from it
        using JsonDocument document = JsonDocument.ParseValue(ref reader);
        return JToken.Parse(document.RootElement.GetRawText());
    }

    public override void Write(Utf8JsonWriter writer,

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@gregsdennis
Comment options

@benbenwilde
Comment options

Answer selected by snjosephms
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
5 participants
Converted from issue

This discussion was converted from issue #82167 on February 15, 2023 18:35.