3 回答
TA贡献1887条经验 获得超5个赞
不要声明你不想要的字段。
https://play.golang.org/p/cQeMkUCyFy
package main
import (
"fmt"
"encoding/json"
)
type Struct struct {
Title string `json:"title"`
}
func main() {
test := `{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}`
var s Struct
json.Unmarshal([]byte(test), &s)
fmt.Printf("%#v", s)
}
或者,如果您想完全摆脱结构:
var i interface{}
json.Unmarshal([]byte(test), &i)
fmt.Printf("%#v\n", i)
fmt.Println(i.(map[string]interface{})["title"].(string))
或者。它会吞下所有的转换错误。
m := make(map[string]string)
json.Unmarshal([]byte(test), interface{}(&m))
fmt.Printf("%#v\n", m)
fmt.Println(m["title"])
TA贡献1851条经验 获得超3个赞
要扩展 Darigaaz 的答案,您还可以使用在解析函数中声明的匿名结构。这避免了必须让包级别的类型声明在单一用例的代码中乱扔垃圾。
https://play.golang.org/p/MkOo1KNVbs
package main
import (
"encoding/json"
"fmt"
)
func main() {
test := `{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}`
var s struct {
Title string `json:"title"`
}
json.Unmarshal([]byte(test), &s)
fmt.Printf("%#v", s)
}
TA贡献1829条经验 获得超4个赞
查看go-simplejson
例子:
js, err := simplejson.NewJson([]byte(`{
"test": {
"string_array": ["asdf", "ghjk", "zxcv"],
"string_array_null": ["abc", null, "efg"],
"array": [1, "2", 3],
"arraywithsubs": [{"subkeyone": 1},
{"subkeytwo": 2, "subkeythree": 3}],
"int": 10,
"float": 5.150,
"string": "simplejson",
"bool": true,
"sub_obj": {"a": 1}
}
}`))
if _, ok = js.CheckGet("test"); !ok {
// Missing test struct
}
aws := js.Get("test").Get("arraywithsubs")
aws.GetIndex(0)
- 3 回答
- 0 关注
- 127 浏览
添加回答
举报