I am learning ASP.Net MVC5. And I have a case where I need to return a JSON result. Currently, I have list of integer. But I want to return it as json objects. Below is what I have
[HttpGet]
public ActionResult hello()
{
var x = SMS_DAL._DalColl.lstOfID;
return Json(x, JsonRequestBehavior.AllowGet);
}
Observation: the variable x
contains list of integer
. And I want to return it as JSON objects. Below is how x
looks like during VS debugging.
X Count = 3
[0] -1
[1] 2134....
[2] 28463
I have studied JSON and it contains of key value pair like below:
{
"id": 1,
"name": "A green door",
"price": 12.50,
}
So, I ran the controller action and checked the values in Advanced Rest Client.
We can clearly see the value I got are like below
[Array[3]
0: -1
1: 2134...
2: 2843
]
Where are the "double quotes" and where are the "curly braces" representing key and values. Why don't I see them. The result that I am getting are they actually JSON? please guide me.
No matter what you have into list inside, you can return it as Json. You code should be looking something like this :
public ActionResult GetNewChatPosts()
{
List integerList = new List<int>();
return Json(list);
}
Your action is returning an array and that is correct JSON object. Basically, any array is a JSON object if it holds appropriate values - string, number, object, array, boolean or null.
Quick read: https://www.w3schools.com/js/js_json_arrays.asp
If you want a key for the array, return an object in JSON format:
public class TestAPIController : Controller
{
[HttpGet]
public ActionResult Data()
{
return Json(new ArrayResult { Arr = new int[] { 1, 2, 3 } });
}
}
public class ArrayResult
{
public int[] Arr { get; set; }
}
this will return:
{arr: [1,2,3]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.