dougu3290 2019-08-05 05:27
浏览 145
已采纳

如何正确将json字符串转换为对象

I have a Beam pipeline written in Go and I'd like to transform this input:

{"name": "Bob", "age": 32}

to a valid "object".

The go sdk has this function in the encoding package :

// UnmarshalJSON sets the state of this instance from the passed in JSON.
func (w *EncodedType) UnmarshalJSON(buf []byte) error {
    var s string
    if err := json.Unmarshal(buf, &s); err != nil {
        return err
    }
    t, err := graphx.DecodeType(s)
    if err != nil {
        return err
    }
    w.T = t
    return nil
}

But I don't understand how to use it as a step of my pipeline.

  • 写回答

1条回答 默认 最新

  • dongqie5529 2019-08-05 16:09
    关注

    You're sort of on the right track. Go doesn't have "objects" in the normal sense of the word as it pertains to programming. You would use a struct like this:

        type User struct {
            Name    string `json:"name"`
            Age     int    `json:"age"`
        }
    

    You would use that to unmarshal into that structure like this:

        var myUser User
        err := json.Unmarshal([]byte(`{"name": "Bob", "age": 32}`), &myUser)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(myUser.Name, myUser.Age)
    

    Here is a playground example: https://play.golang.org/p/_uHZ9Q_j-p1

    More information: https://blog.golang.org/json-and-go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵