如何移除API响应中的元数据?附代码示例
移除API响应中的$id、$values元数据方案
问题说明
API返回的JSON包含$id、$values这类冗余元数据,需要移除这些字段,让响应结构符合预期的简洁格式。
当前响应
{ "$id": "1", "statusCode": 200, "message": { "$id": "2", "$values": [ { "$id": "3", "id": 3, "comment": "hello", "createdAt": "2024/1/29", "student": "Student Mahmoud", "lessonId": 1011 } ] } }
现有返回代码
return StatusCode( 200, new { statusCode = 200, studentCourses } );
其中studentCourses为数据库查询结果。
期望目标响应
{ "statusCode": 200, "message": [ { "id": 3, "comment": "hello", "createdAt": "2024/1/29", "student": "Student Mahmoud", "lessonId": 1011 } ] }
解决方法
1. 修正返回对象的属性名
现有代码返回的是studentCourses字段,与期望响应的message字段不符,先调整属性名:
return StatusCode( 200, new { statusCode = 200, message = studentCourses // 将字段名改为message } );
2. 将数据库结果转为普通集合
$values字段通常是直接返回EF的DbSet或IQueryable对象导致的,提前将结果转为List或数组,避免序列化时生成包装结构:
// 先将数据库查询结果转为List var studentCoursesList = studentCourses.ToList(); return StatusCode( 200, new { statusCode = 200, message = studentCoursesList } );
3. 调整JSON序列化配置
$id字段是序列化器处理循环引用时生成的,通过配置关闭引用保留即可移除:
若使用System.Text.Json(.NET Core 3.0+默认)
在Program.cs或Startup.cs中添加序列化配置:
builder.Services.AddControllers() .AddJsonOptions(options => { // 忽略循环引用,避免生成$id options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // 可选:格式化输出JSON options.JsonSerializerOptions.WriteIndented = true; });
若使用Newtonsoft.Json(Json.NET)
如果项目使用Newtonsoft.Json作为序列化器,配置如下:
builder.Services.AddControllers() .AddNewtonsoftJson(options => { // 忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 关闭引用保留,移除$id字段 options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; });
效果验证
完成上述调整后,API将返回符合期望的结构,不再包含$id和$values元数据。
内容的提问来源于stack exchange,提问作者Hossam Elsayed
相关产品推荐
相关产品推荐

