Go map转json

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

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

go 复制代码
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))
}

输出为:

go 复制代码
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:

go 复制代码
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 大致代码如下:

go 复制代码
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
相关推荐
c4fx12 分钟前
Delphi5利用DLL实现窗体的重用
开发语言·delphi·dll
鸽芷咕36 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
Jhxbdks1 小时前
C语言中的一些小知识(二)
c语言·开发语言·笔记
java6666688881 小时前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存1 小时前
源码分析:LinkedList
java·开发语言
代码雕刻家1 小时前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
Fan_web1 小时前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
liupenglove1 小时前
golang操作mysql利器-gorm
mysql·golang
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
风等雨归期1 小时前
【python】【绘制小程序】动态爱心绘制
开发语言·python·小程序