Live Chat Icon For mobile
Live Chat Icon

How do I serialize and deserialize JSON in a Blazor application?

Platform: Blazor| Category: General

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.

@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

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.