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

如何通过Azure Function将HTTP POST原始JSON直接写入CosmosDB

问题描述

需要将HTTP POST请求的原始JSON正文直接写入CosmosDB,输入原始JSON如下:

{
  "id": "123456",
  "storeName": "City Bar and Grille",
  "invoiceTotal": 65
}

当前使用documentsOut.AddAsync的代码会自动生成随机ID,并将原始JSON嵌套在body字段下:

await documentsOut.AddAsync(new
{
    // 创建随机ID
    id = System.Guid.NewGuid().ToString(),
    body = sourceJson
});

写入CosmosDB后的文档结构不符合需求:

{
  "id": "0e99d3ab-1956-4c0a-8ec1-99de5c987555",
  "body": {
    "id": "123456",
    "storeName": "City Bar and Grille",
    "invoiceTotal": 65
  }
}

期望得到的文档结构是直接保留原始JSON的所有字段,不生成随机ID,也不嵌套在父节点中:

{
  "id": "123456",
  "storeName": "City Bar and Grille",
  "invoiceTotal": 65
}
解决方案

根据sourceJson的类型,分两种情况处理:

情况1:sourceJson已反序列化为.NET对象(dynamic或强类型模型)

直接将该对象传入AddAsync方法即可,无需包装匿名对象:

await documentsOut.AddAsync(sourceJson);

这种方式会直接使用原始JSON中的id字段作为CosmosDB文档的ID,同时保留所有其他字段,不会生成随机ID或添加额外父节点。

情况2:sourceJson是原始JSON字符串

需要先将JSON字符串反序列化为.NET对象,再传入AddAsync,可通过以下方式实现:

使用System.Text.Json(.NET内置库)

// 反序列化为dynamic对象,适用于不确定JSON结构的场景
var document = System.Text.Json.JsonSerializer.Deserialize<dynamic>(sourceJson);
await documentsOut.AddAsync(document);

使用强类型模型(推荐,类型更安全)

先定义与JSON结构匹配的模型类:

public class Invoice
{
    public string id { get; set; }
    public string storeName { get; set; }
    public decimal invoiceTotal { get; set; }
}

再反序列化并写入:

var invoice = System.Text.Json.JsonSerializer.Deserialize<Invoice>(sourceJson);
await documentsOut.AddAsync(invoice);

使用Newtonsoft.Json(若项目已引用)

var document = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(sourceJson);
await documentsOut.AddAsync(document);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:41:16