JsonDocument 获取 JSON 字符串

JsonDocument Get JSON String

我需要一个从 JsonDocument 获取 JSON 字符串的示例。我可以使用 RootElement.GetProperty("ItemName") 获取属性然后调用 .GetString() 但看不到将根元素作为 JSON 字符串获取的方法?

举个例子:

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());
}

为了更容易使用,您可以将其放在扩展方法中,例如:

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());
    }
}

并像这样使用它:

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

作为记录,官方文档中有 2 个代码片段 How to serialize and deserialize (marshal and unmarshal) JSON in .NET


一个。 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.

乙。 Use Utf8JsonWriter

The following example shows how to use the Utf8JsonWriter class:

(...)

截图可以调整使用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());