Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ASP.NET MVC中格式化JSON_Asp.net_Asp.net Mvc_Json - Fatal编程技术网

在ASP.NET MVC中格式化JSON

在ASP.NET MVC中格式化JSON,asp.net,asp.net-mvc,json,Asp.net,Asp.net Mvc,Json,我想从ASP.NET MVC ActionResult类型方法返回一个JSON,该方法如下所示: { success: true, users: [ {id: 1, FileName: 'Text22'}, {id: 2, FileName: 'Text23'} ] } 我将如何格式化它?现在我有这样的东西 Return Json(New With {Key .success = "true", Key .users = responseJsonSt

我想从ASP.NET MVC ActionResult类型方法返回一个JSON,该方法如下所示:

{
     success: true,
     users: [
    {id: 1, FileName: 'Text22'},
    {id: 2, FileName: 'Text23'}
    ]
}
我将如何格式化它?现在我有这样的东西

Return Json(New With {Key .success = "true", Key .users = responseJsonString}, JsonRequestBehavior.AllowGet)
编辑:我正在使用VB.NET,但C语言的答案也不错。

C语言#

返回


{“success”:true,“users”:[{“id”:1,“FileName”:“Text22”},{“id”:2,“FileName”:“Text23”}]}

我更喜欢使用ViewModels,而不是手动构建复杂的JSON响应。它确保了针对所有返回数据的方法的一致性,并且更容易使用强类型属性IMHO

public class Response
{
    public bool Success { get; set; }
    public IEnumerable<User> Users { get; set; }
}

public class User 
{
    public int Id { get; set; }
    public string Name { get; set; }
}
如果存在诸如成功状态或错误消息之类的公共数据,则这还具有允许您对每个响应使用基类的优点

public class ResponseBase
{
    public bool Success { get; set; }
    public string Message { get; set; }
}

public class UserResponse : ResponseBase
{ 
    IENumerable<User> Users { get; set }
}
或者如果成功了

return Json(new UserResponse() { Success = true, Users = users });
如果您想手动创建JSON,那么只需:

Response response = new Response();
response.Success = true;
// populate the rest of the data

return Json(response);
return Json(new { success = true, users = new[] { new { id = 1, Name = "Alice"}, new { id = 2, Name = "Bob"} } });
return Json(new UserResponse() { Success = true, Users = users });
return Json(new { success = true, users = new[] { new { id = 1, Name = "Alice"}, new { id = 2, Name = "Bob"} } });