英文:
Golang Json.Marshal error
问题
我一直在尝试将地图编码为JSON,但迄今为止没有成功。Json.Marshal只编码键,而不是值。
以下是您提供的代码的翻译:
package main
import (
"encoding/json"
"fmt"
)
type node struct {
value string
expiry float64
settime float64
}
func main() {
var x = make(map[string]node)
x["hello"] = node{value: "world", expiry: 1, settime: 2}
x["foo"] = node{value: "bar", expiry: 1, settime: 2}
a, err := json.Marshal(x)
fmt.Println(string(a))
}
输出结果:
{"foo":{},"hello":{}}
希望这可以帮助到您。
英文:
I have been trying to encode a map into JSON but I have been unsuccessful so far. Json.Marshal is not encoding value, its just encoding the key.
https://gist.github.com/rahulpache/9174490
package main
import (
"encoding/json"
"fmt"
)
type node struct {
value string
expiry float64
settime float64
}
func main() {
var x = make(map[string]node)
x["hello"] = node{value: "world", expiry: 1, settime: 2}
x["foo"] = node{value: "bar", expiry: 1, settime: 2}
a, err := json.Marshal(x)
fmt.Println(string(a))
}
Output:
{"foo":{},"hello":{}}
答案1
得分: 10
你的属性和类型名称是私有的,如果你希望属性是公开的,你需要遵循每个单词首字母大写的约定(例如,使用"Value"而不是"value"),以使其成为公开的。将你的类型修改为以下形式,它应该可以正常序列化。
type Node struct {
Value string
Expiry float64
Settime float64
}
英文:
Your properties and the type name are private, if you want your properties to be public you need to follow the convention of capitalizing each word e.g. (Value instead of value) to make it public, switch your type to this and it should serialize just fine.
type Node struct {
Value string
Expiry float64
Settime float64
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论