Go map转json

在Go中如何返回前端 字段名称/数量都不确定的json数据?

之前用Go写web服务,返回给前端的json格式的接口,有哪些要返回的字段都是明确的。都是预先定义一个结构体,json.Marshal一下即可~

但当有的场景,要返回哪些字段不确定时,就无法使用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 复制代码
var rs xxxxx
mapInstance["default"] = mapDefault

jsonByteSli, err := json.Marshal(mapInstance)


v := &structpb.Value{}

err = protojson.Unmarshal(jsonByteSli, v)

rs.Data = v
return &rs, nil

struct.proto源码: protobuf/src/google/protobuf/struct.proto

Protobuf3 语法指南

相关推荐
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
llz_1127 小时前
web-第三次课后作业
前端·后端·web
MageGojo9 小时前
天气 API 接入实战:基于 ApiZero 实现实时天气、分钟级降水和 15 天预报查询
java·后端·spring·api 接口接入·接口实战
pe7er10 小时前
软件设计不要“既要又要”
前端·后端·架构
柏舟飞流10 小时前
Spring Boot 深入实践指南:从入门到工程化落地
spring boot·后端·firefox
IT_陈寒10 小时前
Java Stream并行流的坑:我花了3小时才找到的线程安全问题
前端·人工智能·后端
橘子海全栈攻城狮10 小时前
【最新源码】鸟博士微信小程序 023
spring boot·后端·web安全·微信小程序·小程序
Hiter_John11 小时前
Golang的运算符
开发语言·后端·golang
皮皮林55111 小时前
Dubbo 的 SPI 和 JDK 的 SPI 有什么区别?
后端
金銀銅鐵11 小时前
用 Tkinter 实现一个罗马数字转整数的简单工具
后端·python