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 language independent. In Blazor, the JsonSerializer class, found in the System.Text.Json namespace, assists with serializing and deserializing JSON data.

[index.razor]

@page "/" 

@using System.Text.Json 
<p>Sample demonstration of serializing and deserializing JSON in a Blazor application.</p> 
<button @onclick="SerializeMethod">Serialize </button> 
<button @onclick="DeserializeMethod">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" }; 
    public string? serializedString { get; set; } 
    void SerializeMethod () 
    { 
        //for serialization 
        serializedString = System.Text.Json.JsonSerializer.Serialize(user); 

    } 
    void DeserializeMethod () 
    { 
        //for deserialization 
        User userCopy = System.Text.Json.JsonSerializer.Deserialize<User>(serializedString); 
    } 
} 

In the provided sample, JsonSerialize.Serialize(object) is used to serialize the user object of the User class into a string. Then, JsonSerialize.Deserialize<ClassName>(JsonObject) is used to deserialize the serializedString string into a new instance of the User class named userCopy

Share with

Related FAQs

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

Please submit your question and answer.