JSON (JavaScript Object Notation) is a lightweight data-interchange format and a text format that is completely language independent. In Blazor, JsonSerializer class helps serialize and deserialize JSON. It is present in the namespace System.Text.Json.
[index.razor]
@page "/"
@using System.Text.Json
<button @onclick="@SerializeDeserializeMethod">Serialize & Deserialize</button>
@code {
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
User user = new User() {ID = 1, Name = "Manas", Address = "India"};
void SerializeDeserializeMethod()
{
//for serialization
string serializedString = System.Text.Json.JsonSerializer.Serialize(User1);
//for deserialization
User userCopy = System.Text.Json.JsonSerializer.Deserialize<User>(serializedString);
}
}
In the sample using JsonSerialize.Serialize(object), the object user of class user is serialized and stored as a string, then using JsonSerialize.Deserialize<ClassName>(JsonObject) the string serializedString is deserialized with respect to class user as userCopy.
Share with