JSON硬编码数据C#

时间:2018-07-20 12:05:43

标签: c# arrays json

我正在用C#手动创建JSON数据。我需要返回JSON结果数组。我想像下面一样返回数组,但是我不想得到Fruits Text。

public JsonResult GetFruits()
        {
            return Json(new
            {
                Fruits = new List<object>
                {
                    new {
                            Color="Red",
                            Name="Apple",
                            Shape="Round"
                        }
                }
            }, JsonRequestBehavior.AllowGet);
        }

它正在显示json结果,如下所示:

    {
    "Fruits": [
        {
            "Color": "Red",
            "Name": "Apple",
            "Shape": "Round"
        }
    ]
}

但是我真正想要的是:

[
        {
            "Color": "Red",
            "Name": "Apple",
            "Shape": "Round"
        }
]

有人有什么主意吗?

2 个答案:

答案 0 :(得分:0)

public JsonResult GetFruits()
        {
            return Json(
                new List<object>
                {
                    new 
                    {
                        Color="Red",
                        Name="Apple",
                        Shape="Round"
                    }
                }, 
                JsonRequestBehavior.AllowGet);
        }

但是!恕我直言,您应该使用颜色,名称,形状道具创建类Fruit,然后像这样使用它:

public JsonResult GetFruits()
{
    var fruits = new List<Fruit>
    {
        new Fruit 
        {
            Color = "Red",
            Name = "Apple",
            Shape = "Round"
        },
        new Fruit 
        {
            Color = "Green",
            Name = "Melon",
            Shape = "Square"
        }
    };

    return Json(fruits, JsonRequestBehavior.AllowGet);
}             

答案 1 :(得分:0)

@JimmyFL已经提供了答案。

我发现了做事的不同方式

 public JsonResult GetFruits()
    {
        return Json(new List<object>
        {
            new {
                    Color="Red",
                    Name="Apple",
                    Shape="Round"
                }
        }, JsonRequestBehavior.AllowGet);
    }

Screen shot of the Code