Golang的Json.Marshal错误

huangapple go评论81阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2014年2月24日 01:38:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/21971843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定