gpt4 book ai didi

json - 解码 JSON 对象以在 Go 中进行结构化 - 结果为空

转载 作者:数据小太阳 更新时间:2023-10-29 03:16:34 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





My structures are not marshalling into json [duplicate]

(3 个回答)


6年前关闭。




我正在尝试将 json 对象解码到 Go 中的结构体。我试着坚持 this example但我无法让它工作。结果保持为空。

代码:

package main

import (
"encoding/json"
"fmt"
)

type MyObject struct {
id string
pubKey string
}

func main() {
x := `{"id":"abc","pubKey":"QIDAQAB"}`
fmt.Println("Input: ", x)

var myObject MyObject
json.Unmarshal([]byte(x), &myObject)

fmt.Println("Output: ", myObject)
}

输出:
Input:  {"id":"abc","pubKey":"QIDAQAB"}
Output: { }

Playground

我找到了一个 lot of similar问题,但我什至看不到工作示例和我的非工作代码之间的区别。我错过了什么?

最佳答案

要编码或解码的结构字段 必须被导出。
看看:http://blog.golang.org/json-and-go

The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.



工作样本: Go playground

关于json - 解码 JSON 对象以在 Go 中进行结构化 - 结果为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32438306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com