-1

I am constructing a string like the following:

List<string> itemList = new List<string>();

foreach (i in items)
{
 itemList.Add("{ type: " + i.DocumentType + " ,id: " + i.ID + " ,name: " + i.name + " }" );
}

I want to convert the itemList to a JSON object and return it as response in my controller.

Please help.

ɐsɹǝʌ ǝɔıʌ
  • 4,440
  • 3
  • 35
  • 56
Aziz Qureshi
  • 281
  • 2
  • 4
  • 14

2 Answers2

4

In ASP.Net MVC you could use Linq to get your List in your desired style and then convert to Json using Json(). ie:

public JsonResult GetMyItems()
{
   var myItems = items.Select(i => new { 
                    type = i.DocumentType,
                    id = i.ID,
                    name = i.name
                 });

   return Json(myItems, JsonRequestBehavior.AllowGet);
}
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
1

See Serializing and Deserializing JSON

public class Data {
 public Data(string type, long id, string name) {
  Type = type;
  Id = id;
  Name = name
 }
 public string Type { get; set; }
 public long Id { get; set; }
 public string Name {get; set;
}

var itemList = items.Select(i => Data(i.DocumentType , i.ID, i.name).ToList();
string json = JsonConvert.SerializeObject(itemList);

Nafis Islam
  • 1,483
  • 1
  • 14
  • 34