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?
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?
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
As of .NET 6.0 (comes with System.Text.Json 6.0.0), JsonSerializer.SerializeToDocument
is available.
JsonDocument doc = JsonSerializer.SerializeToDocument(yourObject);
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...
© 2022 - 2024 — McMap. All rights reserved.
object
parameter. You'll have to serialize the object. – Semiaquatic