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

C#中ProcessResponse与JSON互转的最优方案咨询(ProtoBuffer场景)

解决方案

针对Protobuf生成的ProcessResponse对象的JSON序列化与反序列化问题,最优方案是使用Google官方提供的Protobuf JSON处理工具——仅用JsonFormatter只能完成序列化,反向转换需要配套的官方反序列化工具。

具体实现步骤

  1. 确认依赖安装
    确保项目已安装Google.Protobuf NuGet包,这是官方处理Protobuf对象的核心依赖。

  2. 序列化(ProcessResponse → JSON字符串)
    沿用你已在使用的JsonFormatter完成序列化,代码示例:

    using Google.Protobuf;
    using Google.Protobuf.Json;
    
    ProcessResponse response = GetProcessResponse(); // 你的业务对象实例
    string jsonString = JsonFormatter.Default.Format(response);
    
  3. 反序列化(JSON字符串 → ProcessResponse)
    使用官方的JsonParser完成反向转换,这是解决你当前问题的关键:

    ProcessResponse deserializedResponse = JsonParser.Default.Parse<ProcessResponse>(jsonString);
    

补充说明

如果因特殊场景无法使用官方库,可手动定义与ProcessResponse结构一致的DTO类,通过映射工具(如AutoMapper)在Protobuf对象和DTO间转换,再用Newtonsoft.Json或System.Text.Json处理DTO的序列化反序列化。但这种方式需要维护额外的DTO类,易因Protobuf定义变更出现结构不一致,远不如官方方案简洁可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:52:06