C# by Nélio

JSON Deserialization in C#

The JsonSerializer.Deserialize parses the text representing a single JSON value into an instance of a specified type.

using System.Text.Json;

string json = @"{""Name"":""Krish Jackon"", ""Gender"":""female"",
    ""DateOfBirth"":{""year"":1985,""month"":03,""day"":30}}";

var user = JsonSerializer.Deserialize<User>(json);

Resources to deserialize to dynamic object

...see more

To deserialize JSON into a dynamic object in C# using System.Json, follow these steps:

  1. Parse the JSON string using JsonValue.Parse() to obtain a JsonValue object.
  2. Convert the JsonValue object to a dynamic object using the JsonValue.ToDynamic() extension method.

Here's an example code snippet:

using System.Json;

string jsonString = "{\"name\":\"John\",\"age\":30}";
JsonValue jsonValue = JsonValue.Parse(jsonString);
dynamic dynamicObj = jsonValue.ToDynamic();

Console.WriteLine($"Name: {dynamicObj.name}, Age: {dynamicObj.age}");

For more advanced JSON deserialization scenarios in C#, using libraries like Json.NET (Newtonsoft.Json) is recommended. 

Some helpful links

Comments

Leave a Comment

All fields are required. Your email address will not be published.