栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang protobuf 枚举值 json 解析

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang protobuf 枚举值 json 解析

现有 protobuf 数据结构

enum Phase {
	Pending = 1;
    Running = 0;
}
message Status {
    Phase status = 1;
}

实际生成代码,对应的类型

type Phase int32
const (
	Phase_Pending    Phase = 0
	Phase_Running    Phase = 1
}

但我们希望解析的数据如下

{
	"status":"Pending"
}

常规的 encoding/json 包是无法跨类型解析的,因为 json 数据为 string 类型

这个时候就要用到 github.com/golang/protobuf/jsonpb 这个包来解析

	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	json := jsonpb.Unmarshaler{}
	wf := &workflow.Workflow{}
	err = json.Unmarshal(f, wf)
	if err != nil {
		return nil, err
	}

通过 jsonpb 可以解析 json 到 protobuf 的枚举值
如果希望兼容 json 库,则需要重写对象的 MarshalJSON/UnmarshalJSON 方法,里面使用 jsonpb 包来操作

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908521.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号