What's the counterpart to JObject.FromObject in System.Text.Json
Asked Answered
S

3

20

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?

Sanborn answered 6/3, 2020 at 13:57 Comment(2)
There isn't one. The documentation lists all of the members, and there are no methods which take an object parameter. You'll have to serialize the object.Semiaquatic
Related: System.Text.Json.JsonElement ToObject workaround.Denys
G
11

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

Glyptography answered 6/3, 2020 at 14:39 Comment(0)
S
8

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

JsonDocument doc = JsonSerializer.SerializeToDocument(yourObject);
Stigmatism answered 18/2, 2023 at 13:14 Comment(0)
C
0

The closest match to JObject in System.Text.Json is the JsonObject and it's closely related base class JsonNode that are both available with System.Text.Json for .NET 6...

The prior answer noted JsonDocument via JsonSerializer.SerializeToDocument(yourObject) which you can also do for JsonNode via JsonSerializer.SerializeToNode(yourObject).

As a JsonNode you can then act on it directly via named indexers just like JObject: var value = jsonNode["propName"]?.["childPropName"]?.GetValue<string>();

Or cast it to the expected type for some additional type specific functionality (e.g. Enumeration of Properties or Items): foreach(var prop in jsonBase.AsObject()) or foreach(var item in jsonBase.AsArray())

JsonObject is also mutable so you can update/edit/re-write the json as needed just like with JObject. Just note that if you move a value/property from one JsonNode to another you must remove it from the first before it can be safely appended/added to the other....

A trite example is a game-of-telephone in code:

var myObject = new { GameOfTelephoneInCode = "Woot!" };

var myJsonObject = JsonSerializer.SerializeToNode(myObject).AsObject();
var newJsonObj = new JsonObject();

foreach (var prop in myJsonObject.ToArray()) //Captures all Props as KeyValuePairs
{
          //Must Remove from existing Parent so it can be re-assigned...    
          myJsonObject.Remove(prop.Key);
          newJsonObj[prop.Key] = prop.Value;
}

var telephoneMessage = newJsonObj[nameof(myObject.GameOfTelephoneInCode)]?.GetValue<string>();
Debug.WriteLine($"This game-of-telephone in code sent a message: {telephoneMessage}");

A more complete example of mutating/re-writing Json with a merge implementation is here in my gist...

Calcifuge answered 5/6 at 5:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.