3

I want to create a JsonNode corresponding to a C# object (a POCO).

One way to do this would be to:

string json = JsonSerializer.Serialize(poco); JsonNode? jsonNode = JsonNode.Parse(json); 

Is there a better way to do this?

3
  • A specific poco or just any poco? Commented Oct 10, 2024 at 13:00
  • 1
    What are you trying to achieve here? Not sure why you'd want to go from an object with a concrete type and definite structure to something that doesn't. Either way, did you try JsonSerializer.SerializeToNode? Commented Oct 10, 2024 at 13:00
  • @phuzi I need to manipulate the JSON DOM before doing other stuff, hence the need for JsonNode. I haven't tried SerializeToNode because the documentation makes it sound like it is only for single values, not for a whole POCO. Commented Oct 10, 2024 at 13:08

2 Answers 2

4

You can use the JsonSerializer.SerializeToNode method, which directly serializes the object to a JsonNode:

JsonNode? jsonNode = JsonSerializer.SerializeToNode(poco); 

This way, you skip the overhead of serializing to a string first, making it a bit more efficient.

Edit example:

using System.Text.Json; using System.Text.Json.Nodes; var poco = new { Name = "John Doe", Age = 30 }; JsonNode? jsonNode = JsonSerializer.SerializeToNode(poco); Console.WriteLine(jsonNode); 

Documentation: JsonSerializer.SerializeToNode

Sign up to request clarification or add additional context in comments.

3 Comments

It looks like it still serializes / deserializes under the hood, but it does use a cached buffer
Documentation makes it seem like it only works for simple values (e.g., an int, or decimal or string). Can it work for a complex/free-form POCO (multiple properties, perhaps nested objects, lists of objects etc.)?
From one of the overloads you could see that a type can be passed as a parameter, should work with other types. public static System.Text.Json.Nodes.JsonNode? SerializeToNode (object? value, Type inputType, System.Text.Json.JsonSerializerOptions? options = default);
3

How about JsonSerializer.SerializeToNode

JsonNode? node = JsonSerializer.SerializeToNode(poco); 

2 Comments

Documentation makes it seem like it only works for simple values (e.g., an int, or decimal or string). Can it work for a complex/free-form POCO (multiple properties, perhaps nested objects, lists of objects etc.)?
@markvgti Works fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.