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

如何在C#中创建符合指定Schema输出结构的模型类

你给出的目标Schema示例存在语法错误,JSON数组内不能直接包含"key":value格式的键值对,推测你实际需要的合法输出结构如下:

{
  "Food": {
    "items": ["burger", "french fries", "nuggets"],
    "status": "delivered"
  }
}

正确的C#模型编写方式

你原有代码的问题在于多嵌套了一层不必要的item类,不需要将食物列表和状态字段拆分到独立子类中,直接将两个属性定义在Food类下即可:

// 若输出包含外层根节点,定义该类
public class Root
{
    public Food Food { get; set; }
}

public class Food
{
    // 存储食物项列表
    public List<string> Items { get; set; }
    // 存储配送状态
    public string Status { get; set; }
}

序列化输出示例(以System.Text.Json为例)

配置序列化时使用小驼峰命名,即可输出符合常规JSON规范的结构:

var data = new Root
{
    Food = new Food
    {
        Items = new List<string> { "burger", "french fries", "nuggets" },
        Status = "delivered"
    }
};

var jsonOptions = new System.Text.Json.JsonSerializerOptions
{
    PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
    WriteIndented = true
};
string outputJson = System.Text.Json.JsonSerializer.Serialize(data, jsonOptions);

如果不需要外层Root节点,直接序列化Food类的实例即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:15:04