JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easily read and written by humans and parsed and generated by machines. The application/json
is the official Internet media type for JSON. The JSON filename extension is .json.
The System.Text.Json
namespace provides high-performance, low-allocating, and standards-compliant tools to work with JSON. The classes allow us to serialize objects into JSON text and deserialize JSON text to objects. The UTF-8 support is built-in.
The JsonDocument.Parse
parses a stream as UTF-8-encoded data representing a single JSON value into a JsonDocument
. The stream is read to completion.
using System.Text.Json;
string data = @" [ {""name"": ""Krish Jackon"", ""phoneNumber"": ""123456""},
{""name"": ""Marc Moore"", ""phoneNumber"": ""654321""} ]";
using JsonDocument doc = JsonDocument.Parse(data);
JsonElement root = doc.RootElement;
The JsonSerializer.Serialize
converts the value of a specified type into a JSON string.
using System.Text.Json;
var user = new User("Krish Jackon", "female", new MyDate(1985, 03, 30));
var json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
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
Comments