登录
首页 >  Golang >  Go问答

使用 Golang 解析 JSON 数据到生成的 protobuf 结构

来源:stackoverflow

时间:2024-03-14 22:18:26 476浏览 收藏

本篇文章给大家分享《使用 Golang 解析 JSON 数据到生成的 protobuf 结构》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我想通过客户端应用程序请求 json 响应,并将该响应解组到结构中。为了确保使用此包的所有客户端应用程序的结构保持相同,我想将 json 响应定义为 protobuf 消息。我在将 json 解组到 protobuf 生成的结构时遇到困难。

我有以下 json 数据:

[
  {
    "name": "c1",
    "type": "docker"
  },
  {
    "name": "c2",
    "type": "docker"
  }
]

我对 protobuf 定义进行了建模,如下所示:

syntax = "proto3";
package main;

message container {
    string name = 1;
    string type = 2;
}

message containers {
    repeated container containers = 1;
}

将此模式与结构一起使用通常可以工作,但由于某种原因,使用这些原型定义会导致问题。下面的代码演示了一个工作示例和一个非工作示例。尽管其中一个版本有效,但我无法使用此解决方案,因为 []*container 不满足 proto.message 接口。

package main

import (
    "encoding/json"
    "fmt"
    "strings"

    "github.com/gogo/protobuf/jsonpb"
)

func working(data string) ([]*container, error) {
    var cs []*container
    return cs, json.unmarshal([]byte(data), &cs)
}

func notworking(data string) (*containers, error) {
    c := &containers{}
    jsm := jsonpb.unmarshaler{}
    if err := jsm.unmarshal(strings.newreader(data), c); err != nil {
        return nil, err
    }
    return c, nil
}

func main() {
    data := `
[
  {
    "name": "c1",
    "type": "docker"
  },
  {
    "name": "c2",
    "type": "docker"
  }
]`

    w, err := working(data)
    if err != nil {
        panic(err)
    }
    fmt.print(w)

    nw, err := notworking(data)
    if err != nil {
        panic(err)
    }
    fmt.print(nw.containers)
}

运行此命令会产生以下输出:

[name:"C1" type:"docker"  name:"C2" type:"docker" ]
panic: json: cannot unmarshal array into Go value of type map[string]json.RawMessage

goroutine 1 [running]:
main.main()
        /Users/example/go/src/github.com/example/example/main.go:46 +0x1ee

Process finished with exit code 2

有没有办法将此 json 解组到 containers?或者,使 []*container 满足 proto.message 接口?


解决方案


对于消息容器,即

message containers {
    repeated container containers = 1;
}

正确的 json 应如下所示:

{
   "containers" : [
      {
        "name": "c1",
        "type": "docker"
      },
      {
        "name": "c2",
        "type": "docker"
      }
    ]
}

如果您无法更改 json,那么您可以使用您创建的函数

func working(data string) ([]*Container, error) {
    var cs []*Container
    err := json.Unmarshal([]byte(data), &cs)
    // handle the error here
    return &Containers{
       containers: cs,
    }, nil
}

理论要掌握,实操不能落!以上关于《使用 Golang 解析 JSON 数据到生成的 protobuf 结构》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>