3

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?

1 Answer 1

15

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't message be followed by ` = ` insted of : ?
Yes, you are rigt @MarkBenovsky, thanks. (javascript confusing) haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.