-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.

8
  • What framework are you using? ASP.NET Web API? ASP.NET MVC? ASP.NET Core MVC? Commented Apr 28, 2020 at 16:37
  • Thank you for your response. I am using ASP.Net MVC Commented Apr 28, 2020 at 16:40
  • I am also using Newtonsoft.Json.Linq; and Newtonsoft.Json. Commented Apr 28, 2020 at 16:42
  • 1
    why are you constructing List<string> instead of creating a list of objects? Commented Apr 28, 2020 at 16:42
  • 1
    Did you read the Newtonsoft documentation? It shows lots of examples. And there are many many other examples online using that library, including on this site. It should not be hard to search for. Do you really need to ask people to repeat it again? Do some basic research, then ask us if you have a problem with the code you're trying. Or check the answers below, which already show examples for you. Commented Apr 28, 2020 at 16:46

2 Answers 2

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

Comments

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);

1 Comment

Note that this is not what OP wants to do even if they try to ask for it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.