Thursday, April 29, 2021

C# MVC JSON Serialization Simple Example

Download using System.Text.Json package from
 Nu-Get solution if using System.Text.Json; shows error.

Click Tools > NuGet Package manager > Manage NuGet Package for solution or Shortcut ALT T,NN. Click Browse Tab. type System.Text.Json in Search Box. Click Install button. 
Description:
Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.

Commonly Used Types:
System.Text.Json.JsonSerializer
System.Text.Json.JsonDocument
System.Text.Json.JsonElement
System.Text.Json.Utf8JsonWriter
System.Text.Json.Utf8JsonReader




Create a Model class named Class1.cs

using System;

namespace MvcSerialization.Models
{
    public class Class1
    {
        public string ProductName { get; set; }
        public DateTimeOffset MfgDate { get; set; }
        public int Price { get; set; }
        public string Description { get; set; }
    }
}

In the HomeController.cs, write the following code.

using MvcSerialization.Models;
using System;
using System.Text.Json;
using System.Web.Mvc;

namespace MvcSerialization.Controllers
{

    public class HomeController : Controller
    {
        // GET: Home
        public string Index()
        {
            Class1 obj = new Class1();
            obj.ProductName = "Paracetamol";
            obj.MfgDate = DateTime.Now;
            obj.Price = 12;
            obj.Description = "This drug is used to treat mild to moderate pain from headaches, menstrual periods, toothaches, backaches, osteoarthritis, or flu aches and pains.";
            string jsonString = JsonSerializer.Serialize(obj);
            return jsonString;
        }
    }
}

OUTPUT:

{"ProductName":"Paracetamol","MfgDate":"2021-04-29T17:26:47.3562527+05:30","Price":12,"Description":"This drug is used to treat mild to moderate pain from headaches, menstrual periods, toothaches, backaches, osteoarthritis, or flu aches and pains."}













No comments:

Post a Comment

Hot Topics