-2

I have the variables which has values in as follows:

var Name = "ABC";
var address = "cde";
var id = 2;

I want to form the JSON string using above as

var jsonObj = {"Name":"cde","Address":"cde","id":2};

these variable are not static, but here I had shown just for the understanding. These variable gets assigned some values based on some logic , but end goal is to have the jsonObj value as

{"Name":"cde","Address":"cde","id":2}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
krity
  • 49
  • 3
  • 7

1 Answers1

1

You are looking for json seralization.

SerializeObject() Serializes the specified object to a JSON string.

To seralize values to json format, you need to create one model class, which will look like,

public class JsonObj
{
  string Name { get; set; };
  string Address { get; set; };
  int Id { get; set; };
}

Now create instance of JsonObj class, by assigning values to each property.

JsonObj jObject = new JsonObj()
{
  Name = "ABC" 
  Address = "cde"
  Id = 2
};

Now use NewtonSoft.Json library to serialize your object to json string

string output = JsonConvert.SerializeObject(jObject);

As @Csharpest suggest, you can use Anonymous type as well to serialize

string output = JsonConvert.SerializeObject(new { Name = "ABC", Address = "cde", Id = 2 }); //Here you need not to create model class and instantiation as well 
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44