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

如何去除Couchbase Lite Document toString结果的标识符以在React Native中解析

解决方案

方案1(优先推荐):Java侧转换为标准JSON返回

该方案稳定性最高,不会受Couchbase Lite版本迭代影响。
Java侧修改返回逻辑:

Document doc = database.getDocument("id");
// 把Document对象转为Map结构
Map<String, Object> docContent = doc.toMap();
// 用项目内置的JSON序列化工具将Map转为JSON字符串
// 以下是用Gson序列化的示例,你也可以替换为Jackson等其他工具
Gson gson = new Gson();
String jsonResult = gson.toJson(docContent);
promise.resolve(jsonResult);

React Native侧直接解析即可:

const documentStr = getNativeDocument('id');
const docData = JSON.parse(documentStr);

方案2:临时解析当前toString输出结果

如果暂时无法修改原生侧代码,可以通过正则匹配提取有效数据,参考JS代码如下:

function parseCbDocString(docStr) {
  // 提取Document对象内的有效内容,过滤头部元数据
  const contentPart = docStr.match(/^Document\{[^:]+:(.*)\}$/)?.[1];
  if (!contentPart) return null;
  // 转换格式适配JSON规则
  const formatStr = contentPart
    // 处理嵌套Dictionary结构
    .replace(/Dictionary\{([^}]+)\}/g, '{$1}')
    // 替换键值分隔符
    .replace(/=>/g, ':')
    // 给键加双引号
    .replace(/([\w]+)\s*:/g, '"$1":')
    // 给非null的字符串值加双引号
    .replace(/:([A-Za-z][^,}]*)([,}])/g, (match, val, end) => {
      if (val === 'null') return `:null${end}`;
      return `:"${val}"${end}`;
    });
  try {
    return JSON.parse(`{${formatStr}}`);
  } catch (err) {
    return null;
  }
}

// 调用示例
const rawStr = getNativeDocument('id');
const docData = parseCbDocString(rawStr);

该方案强依赖当前Couchbase Lite的toString输出格式,版本更新后可能失效,仅作为临时方案使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:39:00