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

.NET Core中如何返回符合预期格式的MongoDB JSON数据

解决.NET Core中MongoDB查询返回JSON格式不符合预期的问题

你的问题出在直接用了MongoDB默认的ToJson()方法——它会按照Bson的规则序列化数据,所以把ObjectId、ISODate这些MongoDB特有类型输出成了非标准的JSON格式;而且你提前把查询结果转成JSON字符串再塞进report,导致返回的value是个字符串而非标准的JSON数组。这里给你两种实用的解决办法:

方法一:配置MongoDB的JSON序列化规则,直接输出标准JSON

你可以通过JsonWriterSettings指定序列化规则,让MongoDB输出符合标准的JSON格式,同时把ObjectId转为字符串、日期转为ISO标准字符串:

// 创建JSON写入配置
var jsonSettings = new JsonWriterSettings
{
    OutputMode = JsonOutputMode.Strict, // 启用严格标准JSON输出
    DateTimeConverter = DateTimeConverter.IsoDateTime, // 将日期转为ISO 8601格式字符串
    GuidRepresentation = GuidRepresentation.Standard
};

// 查询数据并按标准规则序列化
var docs = Collection.Find(new BsonDocument()).ToEnumerable();
var standardJson = docs.ToJson(jsonSettings);

report.Add("value", standardJson);
returnData.Add("obj", report);
returnData.Add("value", 1);
returnData.Add("info", "Reports Retrived Successfully");

方法二:映射到DTO对象,使用.NET标准JSON序列化

这种方法更灵活,适合长期维护的项目——通过定义和MongoDB文档结构匹配的DTO类,把Bson对象转成普通.NET对象后再序列化,能完全控制输出格式:

步骤1:定义DTO类

using System.Text.Json.Serialization;

public class ReportItem
{
    // 将MongoDB的_id映射为字符串类型
    [JsonPropertyName("_id")]
    public string Id { get; set; }

    // 将createddate映射为DateTime,序列化后自动转为ISO标准日期字符串
    [JsonPropertyName("createddate")]
    public DateTime CreatedDate { get; set; }

    // 添加你的其他业务字段...
}

步骤2:查询并映射为DTO集合

using MongoDB.Driver;
using System.Text.Json;

// 查询数据并投影为DTO(自动将ObjectId转为字符串)
var reportItems = Collection.Find(new BsonDocument())
    .Project<ReportItem>(Builders<BsonDocument>.Projection
        .Include("_id").ToString("_id") // 把ObjectId转换为字符串
        .Include("createddate")
        // 这里添加其他需要映射的字段
    )
    .ToList();

// 直接将DTO集合加入report,最后对整个returnData序列化时会自动生成标准JSON数组
report.Add("value", reportItems);
returnData.Add("obj", report);
returnData.Add("value", 1);
returnData.Add("info", "Reports Retrived Successfully");

// 如果需要将returnData最终转为JSON字符串,用.NET的System.Text.Json序列化
var finalJson = JsonSerializer.Serialize(returnData);

这样处理后,返回的value会是标准的JSON数组,_id是字符串格式,createddate是ISO标准的日期字符串,完全符合你的预期。

内容的提问来源于stack exchange,提问作者SATHEESH P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:51:31