Create JSON object from string in C#

Dilip picture Dilip · Mar 27, 2018 · Viewed 11k times · Source

I am trying to create a JSON string which contains one container and one array. I can do this by using a stringbuilder but I am trying to find a better way to get the JSON string; I want:

{ "message":{ "text":"test sms"},"endpoints":["+9101234"]} 

I tried this:

string json = new JavaScriptSerializer().Serialize(new
              {
                  text = "test sms",
                  endpoints = "[dsdsd]"
              });

And the output is:

{"text":"test sms","endpoints":"[dsdsd]"}

Any help or suggestions how to get the required format?

Answer

Felipe Oriani picture Felipe Oriani · Mar 27, 2018

In the most recent version of .NET we have the System.Text.Json namespace, making third party libraries unecessary to deal with json.

using System.Text.Json;

And use the JsonSerializer class to serialize:

var data = GetData();
var json = JsonSerializer.Serialize(data);

and deserialize:

public class Person
{
   public string Name { get; set; }
}

...
var person = JsonSerializer.Deserialize<Person>("{\"Name\": \"John\"}");

Other versions of .NET platform there are different ways like the JavaScriptSerializer where the simplest way to do this is using anonymous types, for sample:

string json = new JavaScriptSerializer().Serialize(new
                {
                    message = new { text = "test sms" },
                    endpoints = new [] {"dsdsd", "abc", "123"}
                });

Alternatively, you can define a class to hold these values and serialize an object of this class into a json string. For sample, define the classes:

public class SmsDto
{
   public MessageDto message { get; set; }

   public List<string> endpoints { get; set; }
}

public class MessageDto
{
   public string text { get; set; }
}

And use it:

var sms = new SmsDto()
{
   message = new MessageDto() { text = "test sms" } ,
   endpoints = new List<string>() { "dsdsd", "abc", "123" }
}

string json = new JavaScriptSerializer().Serialize(sms);