ASP.NET Core返回JObject在浏览器/Swagger显示为空对象数组问题
问题原因说明
- 返回JObject显示空:ASP.NET Core 默认使用
System.Text.Json作为序列化器,无法识别Newtonsoft.Json的JObject类型结构,序列化时会丢失内容导致返回空。 - JsonResult带反斜杠:你大概率是将
JObject先转为JSON字符串再传入JsonResult,触发了二次序列化,原本JSON里的双引号被转义,就会出现大量反斜杠。
解决方案
方案1:配置项目使用Newtonsoft.Json序列化器(适合需要保留JObject用法的场景)
- 安装对应版本的NuGet包:
Microsoft.AspNetCore.Mvc.NewtonsoftJson,版本需与你的项目.NET主版本保持一致。 - 在Program.cs(.NET 6+)中注册服务时添加配置:
builder.Services.AddControllers() .AddNewtonsoftJson(); // 新增这行配置
如果是.NET 5及更早版本,在Startup.cs的ConfigureServices方法中添加对应配置即可。
3. 接口保持原写法直接返回JObject即可,不需要改为JsonResult,Swagger可正常展示返回内容,无转义问题。
方案2:改用强类型模型返回(推荐,性能更高、类型安全)
不需要依赖Newtonsoft.Json,直接定义对应结构的实体类,用默认序列化器即可正常工作:
- 定义实体类:
// 县信息实体 public class County { public string county_name { get; set; } public string description { get; set; } public string feat_class { get; set; } public string feature_id { get; set; } public string fips_class { get; set; } public string fips_county_cd { get; set; } public string full_county_name { get; set; } public string link_title { get; set; } public string url { get; set; } public string name { get; set; } public string primary_latitude { get; set; } public string primary_longitude { get; set; } public string state_abbreviation { get; set; } public string state_name { get; set; } } // 返回根对象 public class CountyResponse { public List<County> Everything { get; set; } }
- 调整接口代码:
[HttpGet(Name = "GetCounties")] public CountyResponse Get() { string countiesJson = "{'Everything':[{'county_name':null,'description':null,'feat_class':'Civil','feature_id':'36865'," + "'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua County'" + ",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'}," + "{'county_name':null,'description':null," + "'feat_class':'Civil','feature_id':'36866','fips_class':'H1','fips_county_cd':'3','full_county_name':null,'link_title':null,'url':'http://www.bakercountyfl.org/','name':'Baker County','primary_latitude':'30.33','primary_longitude':'-82.29','state_abbreviation':'FL','state_name':'Florida'}]}"; // 反序列化为强类型对象 CountyResponse response = System.Text.Json.JsonSerializer.Deserialize<CountyResponse>(countiesJson); // 数据操作逻辑 return response; }
补充说明:如果一定要使用JsonResult返回,不要传入序列化后的JSON字符串,直接传入JObject或强类型对象即可,避免触发二次序列化产生反斜杠。
内容的提问来源于stack exchange,提问作者Bike_dotnet
相关产品推荐
相关产品推荐

