You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6.0中如何将List转换为JSON格式返回?

如何将接口返回改为JSON格式

在ASP.NET环境中,你的接口其实默认就会返回JSON格式,但如果需要显式控制或确保结果为JSON,可采用以下几种方式:

方法一:直接返回JsonResult(适用于MVC/Web API)

修改方法返回类型为JsonResult<List<ProjectModel>>,通过Json()方法返回数据:

[HttpGet]
[Route("getproject")]
public JsonResult<List<ProjectModel>> GetProjects()
{
    var projects = new List<ProjectModel>()
                {
                    new ProjectModel() { Id = 1, Project_Name = "abc", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" },
                    new ProjectModel() { Id = 2, Project_Name = "def", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" }
                };
    return Json(projects);
}

方法二:使用IHttpActionResult指定JSON格式(Web API推荐)

将返回类型改为IHttpActionResult,通过Content方法明确指定JSON媒体类型:

[HttpGet]
[Route("getproject")]
public IHttpActionResult GetProjects()
{
    var projects = new List<ProjectModel>()
                {
                    new ProjectModel() { Id = 1, Project_Name = "abc", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" },
                    new ProjectModel() { Id = 2, Project_Name = "def", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" }
                };
    return Content(HttpStatusCode.OK, projects, new JsonMediaTypeFormatter());
}

方法三:全局配置默认返回JSON(避免XML干扰)

如果项目同时配置了XML格式化器,可在WebApiConfig.cs中移除XML格式化器,确保默认返回JSON:

public static void Register(HttpConfiguration config)
{
    // 移除XML格式化器
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    
    // 其他路由配置...
}

注意事项

  • 确保ProjectModel类的属性都是public访问修饰符,否则JSON序列化器无法读取属性值。
  • 如果模型存在循环引用,可在引用属性上添加[JsonIgnore]特性,或在全局配置中设置循环引用处理规则。

内容的提问来源于stack exchange,提问作者M Nasir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:35:24