27

I need an example of getting a JSON string from a JsonDocument. I can get properties with RootElement.GetProperty("ItemName") and then call .GetString() but can't see a way to just get the root element as a JSON string?

1
  • 1
    JsonDocument (and all the other classes in System.Text.Json) are optimized for performance and minimal allocation. Getting the whole document as a string would go against that entirely, and the only thing it can do is serialize itself to a Utf8JsonWriter. Nevertheless, if you really want to, JsonSerializer.Serialize(document.RootElement) seems to do the trick. Commented Oct 14, 2019 at 14:29

3 Answers 3

40

Here an example:

JsonDocument jdoc = JsonDocument.Parse("{\"a\":123}");

using(var stream = new MemoryStream())
{
    Utf8JsonWriter writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
    jdoc.WriteTo(writer);
    writer.Flush();
    string json = Encoding.UTF8.GetString(stream.ToArray());
}

For an easier usage you could put it in an extension method like:

public static string ToJsonString(this JsonDocument jdoc)
{
    using (var stream = new MemoryStream())
    {
        Utf8JsonWriter writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
        jdoc.WriteTo(writer);
        writer.Flush();
        return Encoding.UTF8.GetString(stream.ToArray());
    }
}

And use it like:

JsonDocument jdoc = JsonDocument.Parse("{\"a\":123}");
string json = jdoc.ToJsonString();

Update: if you don't need a formatted output:

string json = jdoc.RootElement.GetRawText();
Sign up to request clarification or add additional context in comments.

2 Comments

It's actually pretty complicated? For example, imagine that JsonDocument is HUGE, do you want the ToString() to be automatically rendered by the debugger? Imagine there's some encoding options, or you want to write it completely to a string? You might want to pretty-print it (or not). There's a million and one trade-offs there to take into account.
Hi, this doesn't seem to work as expected for JsonDocument.Parse("{\"a\":\"123 + 456\"}"); - The result is {"a": "123 \u002B 456"}. How do we cope with that?
11

I have use RootElement to get a JsonElement and then call .ToString().

JsonDocument jdoc = JsonDocument.Parse("{\"a\":123}");
string json = jdoc.RootElement.ToString();

1 Comment

FYI, jdoc.RootElement.ToString() will return the original unparsed string.
2

For the record there are 2 code snippets in official doco at How to serialize and deserialize (marshal and unmarshal) JSON in .NET


A. Use JsonDocument to write JSON

The following example shows how to write JSON from a JsonDocument:

(surprisingly long code snippet here)

The preceding code:

  • Reads a JSON file, loads the data into a JsonDocument, and writes formatted (pretty-printed) JSON to a file.
  • Uses JsonDocumentOptions to specify that comments in the input JSON are allowed but ignored.
  • When finished, calls Flush on the writer. An alternative is to let the writer autoflush when it's disposed.

B. Use Utf8JsonWriter

The following example shows how to use the Utf8JsonWriter class:

(...)

The snipped can be adjusted to use JsonDocument.Parse:

using var stream = new System.IO.MemoryStream();
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
   var jsonDocument = JsonDocument.Parse(content);
   jsonDocument.WriteTo(writer);
}

var formatted = System.Text.Encoding.UTF8.GetString(stream.ToArray());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.