Search code examples
c#pocosystem.text.json

Is there a direct way to go from POCO to JsonNode?


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?


Solution

  • 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