Go map转json

今天分享的知识是 Go 接口。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!

但当有的场景,要返回哪些字段不确定时,就无法使用struct的方式。 还可以用map

python 复制代码
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	Map2Json()
}

func Map2Json() {
	mapInstance := make(map[string]interface{})

	mapInstance["Name"] = "cs"
	mapInstance["Age"] = 28
	mapInstance["Address"] = "杭州"

	relation := make(map[string]interface{})

	relation["father"] = "cuixxxxxxx"
	relation["mother"] = "yinxxxxx"
	relation["wife"] = "pengxx"

	mapInstance["Relation"] = relation

	pet := make(map[string]interface{})
	pet["one"] = "弥弥懵"
	pet["two"] = "黄橙橙"
	pet["three"] = "呆呆"
	pet["four"] = "皮瓜瓜"
	pet["five"] = "斑斑"

	mapInstance["Cat"] = pet

	jsonStr, err := json.Marshal(mapInstance)

	fmt.Println("err is:", err)
	fmt.Println("jsonStr is:", string(jsonStr))
}

输出为:

python 复制代码
err is: <nil>
jsonStr is: {"Address":"杭州","Age":28,"Cat":{"five":"斑斑","four":"皮瓜瓜","one":"弥弥懵","three":"呆呆","two":"黄橙橙"},"Name":"cs","Relation":{"father":"cuixxxxxxx","mother":"yinxxxxx","wife":"pengxx"}}


在proto中如何定义这样的返回值?

如果使用proto来定义接口,如何定义不确定字段名称和数量的返回值?

即上面的 jsonStr,如何定义才能返回给前端?

尝试使用过Any,发现不行(Any的"风评"很不好,介绍时一般和one of出现在一起)

几经探求,发现这种情况该用Struct(或说Value)类型

Is "google/protobuf/struct.proto" the best way to send dynamic JSON over GRPC?(stackoverflow.com/questions/5... "Is "google/protobuf/struct.proto" the best way to send dynamic JSON over GRPC?")
xxxx.proto:

python 复制代码
syntax = "proto3";
package demo;

import "validate/validate.proto";
import "google/api/annotations.proto";
import "google/protobuf/timestamp.proto";
//import "google/protobuf/any.proto";
import "google/protobuf/struct.proto";

rpc Getxxxxx(GetxxxxxReq)  returns (GetxxxxxResp) {
option (google.api.http) = {
	get:"/api/v1/xxxx/xxxx/xxxxxx"
};
}

message GetxxxxxResp {
  google.protobuf.Value data = 1;
}

message GetxxxxxReq {
  // 用户名
  string user_name = 1
  [(validate.rules).string.max_len = 100, (validate.rules).string.min_len = 1];
  
    // 创建时间
  google.protobuf.Timestamp create_time = 2;

}

xxxx.go 大致代码如下:

python 复制代码
ar rs xxxxx
mapInstance["default"] = mapDefault

jsonByteSli, err := json.Marshal(mapInstance)


v := &structpb.Value{}

err = protojson.Unmarshal(jsonByteSli, v)

rs.Data = v
return &rs, nil
相关推荐
2zcode6 分钟前
基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn
米饭不加菜11 分钟前
使用万用表判断三极管(BJT)好坏
java·开发语言
绝世唐门三哥25 分钟前
vue3中页面返回时刷新首页的处理方案
开发语言·前端·javascript
nianniannnn26 分钟前
c++复习自存--流、异常处理、多线程与C++工程规范
开发语言·c++
geovindu35 分钟前
CSharp: Dijkstra Algorithms
开发语言·后端·算法·c#
XR12345678842 分钟前
食品饮料与制药行业GMP合规网络建设:无尘车间的网络不能成为污染源
开发语言·网络·php
学逆向的1 小时前
汇编——位运算
开发语言·汇编·算法·网络安全
zhangjw341 小时前
第29篇:Java伪共享与对象分配:并发性能优化的关键
java·开发语言·性能优化
Java面试题总结2 小时前
Python 开发技巧 · 高级装饰器 —— 从基础到工业级实战
开发语言·python
liulilittle3 小时前
Exhaustive drift-fix simulation V2 — KCC on shared-bottleneck wired path.
开发语言·网络·python·tcp/ip·计算机网络·信息与通信·通信