Convert json string to CLR type

When working with JSON data in C#, it’s common to convert it into native CLR (Common Language Runtime) types for easier manipulation and interaction within your application. In this post, I’ll guide you through the process of converting JSON strings to CLR types using C#.

Assembly Required

Before we dive into the code, make sure to include the following assembly reference in your project:

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;

The JSON Data

Let’s consider the following JSON data as an example:

{
  "data": [
    {
      "category": "Community",
      "name": "Swati",
      "id": "190847514395344",
      "created_time": "2013-01-09T07:24:29+0000"
    },
    {
      "category": "Wine/spirits",
      "name": "Chill with Rémy, India",
      "id": "184640834879687",
      "created_time": "2013-01-08T05:41:59+0000"
    },
    {
      "category": "Fictional character",
      "name": "MAMU",
      "id": "366505623417822",
      "created_time": "2012-12-04T17:51:36+0000"
    }
  ]
}

Creating CLR Classes

Now, let’s define the CLR classes that correspond to this JSON structure:

public class Likes
{
    public List<Like> data { get; set; }
}

public class Like
{
    public string Category { get; set; }
    public string Name { get; set; }
    public string ID { get; set; }
    public string created_time { get; set; }

    public Like()
    {
        // Default constructor
    }
}

Converting JSON to CLR Types

In your C# program, use the following code to convert the JSON string to CLR types:

class Program
{
    static void Main(string[] args)
    {
        string jsonData = /* your JSON string here */;
        
        JavaScriptSerializer js = new JavaScriptSerializer();
        Likes result = js.Deserialize<Likes>(jsonData);
    }
}

In this example, we’re using JavaScriptSerializer to deserialize the JSON string into an instance of the Likes class. Ensure to replace /* your JSON string here */ with your actual JSON data.

By following these steps, you can easily convert JSON strings into native CLR types, providing a structured and type-safe representation of your data within your C# application. This approach enhances code readability and maintainability while making it easier to work with JSON data in your C# projects.

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru