15

With Newtonsoft Json you can convert an object to a JObject by calling JObject.FromObject(object).

Is there a counterpart in System.Text.Json to get a JsonDocument from an object?

Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
  • There isn't one. [The documentation lists all of the members](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsondocument?view=netcore-3.1), and there are no methods which take an `object` parameter. You'll have to serialize the object. – Heretic Monkey Mar 06 '20 at 14:01
  • Related: [System.Text.Json.JsonElement ToObject workaround](https://stackoverflow.com/q/58138793/3744182). – dbc Mar 06 '20 at 15:41

2 Answers2

9

There is an open issue for it.

But now there is no such methods. You can try

 using (JsonDocument document = JsonDocument.Parse(JsonSerializer.Serialize(object)))
 {
    ...
 }

One more issue

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
2

As of .NET 6.0 (comes with System.Text.Json 6.0.0), JsonSerializer.SerializeToDocument is available.

JsonDocument doc = JsonSerializer.SerializeToDocument(yourObject);
snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34