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 ```

相关推荐
YGGP2 分钟前
【Golang】LeetCode 21. 合并两个有序链表
leetcode·链表·golang
看见繁华4 分钟前
GO 教程
开发语言·后端·golang
Yy_Yyyyy_zz7 分钟前
深入理解 Go 的多返回值:语法、编译原理与工程实践
开发语言·后端·golang
AAA.建材批发刘哥9 分钟前
02--C++ 类和对象上篇
开发语言·c++
玄〤9 分钟前
Spring MVC 讲解:从初始化流程到请求参数与 JSON 处理全解析(黑马课程ssm笔记总结)(day5)
java·spring·json·mvc
廋到被风吹走12 分钟前
【Java】【JVM】垃圾回收深度解析:G1/ZGC/Shenandoah原理、日志分析与STW优化
java·开发语言·jvm
xrkhy13 分钟前
Java全栈面试题及答案汇总(3)
java·开发语言·面试
菩提祖师_17 分钟前
量子机器学习在时间序列预测中的应用
开发语言·javascript·爬虫·flutter
刘975317 分钟前
【第22天】22c#今日小结
开发语言·c#
消失的旧时光-194324 分钟前
Freezed + json_serializable:DTO / Domain 分层与不可变模型(入门到落地)-----上篇
flutter·json·dto·domain