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

如何将JSON的type字段整合进content?C#模型实现存疑

实现指定的JSON格式转换

需求说明

需要将MediaModelResponse实例转换为仅包含两个字段的JSON:

  • content:格式为{Type值}//{Content的Base64编码字符串}
  • type:保留原MediaModelResponse.Type的值

具体实现步骤

1. 定义输出用的DTO

先创建一个只包含目标字段的数据传输对象,避免序列化多余字段:

public class MediaOutputDto
{
    public string Content { get; set; }
    public string Type { get; set; }
}

2. 完成模型转换与内容拼接

将原MediaModelResponse实例转换为MediaOutputDto,同时处理Content的Base64编码和字符串拼接:

// 假设已有MediaModelResponse实例mediaResponse
string base64Content = Convert.ToBase64String(mediaResponse.Content);
MediaOutputDto outputDto = new MediaOutputDto
{
    Content = $"{mediaResponse.Type}//{base64Content}",
    Type = mediaResponse.Type
};

3. 序列化为JSON

根据项目使用的JSON库选择序列化方式:

使用System.Text.Json(.NET Core/.NET 5+默认)

using System.Text.Json;

var jsonOptions = new JsonSerializerOptions
{
    WriteIndented = true // 生成格式化的JSON,与示例格式一致
};
string outputJson = JsonSerializer.Serialize(outputDto, jsonOptions);

使用Newtonsoft.Json(Json.NET)

using Newtonsoft.Json;

string outputJson = JsonConvert.SerializeObject(outputDto, Formatting.Indented);

注意事项

  • 如果mediaResponse.Content为null,调用Convert.ToBase64String会抛出异常,建议提前做空值判断
  • 如果mediaResponse.Type为空字符串,拼接后的content会以//开头,若业务不允许这种情况,需额外处理空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:55:24