简体   繁体   English

如何在ASP.net MVC 5中将整数列表作为JSON对象返回

[英]How to return list of integer as JSON objects in ASP.net MVC 5

I am learning ASP.Net MVC5. 我正在学习ASP.Net MVC5。 And I have a case where I need to return a JSON result. 而且我有一种情况需要返回JSON结果。 Currently, I have list of integer. 目前,我有整数列表。 But I want to return it as json objects. 但我想将其作为json对象返回。 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 . 观察:变量x包含list of integer And I want to return it as JSON objects. 我想将其作为JSON对象返回。 Below is how x looks like during VS debugging. 以下是x在VS调试期间的外观。

X    Count = 3
  [0]   -1
  [1]    2134....
  [2]    28463

I have studied JSON and it contains of key value pair like below: 我研究了JSON,它包含如下所示的键值对:

{
    "id": 1,
    "name": "A green door",
    "price": 12.50,
}

So, I ran the controller action and checked the values in Advanced Rest Client. 因此,我运行了控制器操作,并检查了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? 我得到的结果是它们实际上是JSON吗? please guide me. 请指导我。

No matter what you have into list inside, you can return it as Json. 不管列表中包含什么内容,都可以将其作为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. 您的操作正在返回一个数组,该数组是正确的JSON对象。 Basically, any array is a JSON object if it holds appropriate values - string, number, object, array, boolean or null. 基本上,任何数组如果具有适当的值(字符串,数字,对象,数组,布尔值或null),则都是JSON对象。
Quick read: https://www.w3schools.com/js/js_json_arrays.asp 快速阅读: https : //www.w3schools.com/js/js_json_arrays.asp

If you want a key for the array, return an object in JSON format: 如果您想要数组的键,请以JSON格式返回一个对象:

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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM