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

使用C# Couchbase SDK时UpsertAsync不支持JsonObject的问题求助

解决C# Couchbase SDK插入System.Text.Json.JsonObject时的自引用循环错误

问题根源

Couchbase .NET SDK默认依赖Newtonsoft.Json进行序列化操作,而你使用的是System.Text.Json的JsonObject类型。JsonObject内部的parent属性会触发Newtonsoft.Json的循环引用检测逻辑,从而抛出序列化异常;直接传入JSON字符串会被SDK二次序列化,导致文档出现多余转义字符和引号。


解决方案

方案1:将System.Text.Json.JsonObject转换为Newtonsoft.Json.Linq.JObject

利用Couchbase SDK对Newtonsoft JObject的原生支持,先把JsonObject转回JSON字符串,再解析为JObject后插入:

// 将JsonObject转回原始JSON字符串
string rawJson = jsonToProduce.ToString();
// 用Newtonsoft.Json解析为JObject
Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(rawJson);
// 执行Upsert操作
await collection.UpsertAsync("target-document-key", jObject);

方案2:配置Couchbase SDK使用System.Text.Json作为序列化器

修改Cluster初始化配置,指定使用SystemTextJsonSerializer,这样可以直接传入JsonObject而无需类型转换:

var clusterOptions = new ClusterOptions
{
    ConnectionString = "couchbase://your-cluster-address",
    UserName = "your-username",
    Password = "your-password",
    // 替换默认序列化器为System.Text.Json实现
    Serializer = new SystemTextJsonSerializer()
};

using var cluster = await Cluster.ConnectAsync(clusterOptions);
var bucket = await cluster.BucketAsync("your-bucket-name");
var collection = bucket.DefaultCollection();

// 现在可直接传入JsonObject执行Upsert
await collection.UpsertAsync("target-document-key", jsonToProduce);

注意:需要提前安装Couchbase.Extensions.SystemTextJson NuGet包。

方案3:直接插入原始JSON字符串(避免二次序列化)

如果无需处理JSON对象,可将原始JSON字符串包装为RawJsonDocument,让Couchbase直接存储原始内容:

var rawDoc = RawJsonDocument.Create("target-document-key", jsonString);
await collection.UpsertAsync(rawDoc);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 12:57:03