Create Json Objects in DOTNet

We already know creating JSON Objects in PHP or Python,

but in Dotnet, It works differently so we have to create it in a different way,

Firstly, We have to create a StringBuilder object as well as a JsonTextWriter object as below.

var stringBuilder = new StringBuilder();
 var jsonWriter = new JsonTextWriter(new StringWriter(stringBuilder));

Secondly, If any exceptions occur, Then to handle them we will assign StringEscapeHandling.EscapeNonAscii;

to jsonWriter.StringEscapeHandling object, as below .

 jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;

Thirdly, Start adding values to jsonWriter, as below.

      jsonWriter.WriteStartObject();
      jsonWriter.WritePropertyName("name");
      jsonWriter.WriteValue("Ename");
      jsonWriter.WriteEndObject();

fourthly, We have to convert our json to a string and assign it to a variable , as below.

var encodedArgs = stringBuilder.ToString();

Example:

      var stringBuilder = new StringBuilder();
      var jsonWriter = new JsonTextWriter(new StringWriter(stringBuilder));
      jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
//inserting first object
      jsonWriter.WriteStartObject();
      jsonWriter.WritePropertyName("name");
      jsonWriter.WriteValue("Ename");
      jsonWriter.WriteEndObject();
//inserting second object
      jsonWriter.WriteStartObject();
      jsonWriter.WritePropertyName("mobile");
      jsonWriter.WriteValue("86866454");
      jsonWriter.WriteEndObject(); 
      var encodedArgs = stringBuilder.ToString();

Thank you.

Sign In or Register to comment.