我正在尝试读取一个看起来像这样的 json 文件
[{ "title": "hi", "tags": [1,2,3,4,5,6] }, {...}, {...}]
代码是这样的
contentdat, err := ioutil.ReadFile("content.json")
check(err)
var content []interface{}
err = json.Unmarshal(contentdat, &content)
check(err)
for i, contentItem := range content {
vertedContentItem := contentItem.(map[string]interface{})
contentTags := vertedContentItem["tags"].([]interface{})
contentItemTags := make([]int, len(contentTags))
for i, ctv := range contentTags {
contentItemTags[i] = int(ctv.(float64))
}
我想弄清楚的是如何避免进行所有类型转换并直接访问 json obj 或者可能只对整个 json 结构进行一次类型转换。我想到了像这样定义内部对象的结构
type Content struct {
title string
tags []int
}
然后声明内容为
var content []Content
而不是 interface{} 并按预期循环遍历结构,但这没有用。有什么想法吗?
最佳答案
您必须使用大写字母导出您希望反序列化的“内容”结构的字段:
type Content struct {
Title string
Tags []int
}
例如:
type Content struct {
Title string
Tags []int
}
func main() {
jsonstr := `[{"title":"hi","tags":[1,2,3,4,5,6]}]`
contents := []Content{}
err := json.Unmarshal([]byte(jsonstr), &contents)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", contents)
// => []main.Content{main.Content{Title:"hi", Tags:[]int{1, 2, 3, 4, 5, 6}}}
}
关于json 和类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912327/