douduan5753 2017-12-20 18:31
浏览 57
已采纳

json和类型转换

I am attempting to read a json file that looks like

 [{ "title": "hi", "tags": [1,2,3,4,5,6] }, {...}, {...}]

and the code looks like this

 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))
    }

what I am trying to figure out is how I can avoid the doing all the type casting and just access the json obj directly or maybe just type cast once for the entire json structure. I had a idea about defining the structure of the internal object like so

type Content struct {
  title string
  tags []int
}

and then declare content as

var content []Content

instead of interface{} and just loop through the structure as expected but that didn't work. Any ideas?

  • 写回答

1条回答 默认 最新

  • dongxie2749 2017-12-20 19:04
    关注

    You must export the fields of the "Content" struct that you wish to de/serialize by using capital letters:

    type Content struct {
      Title string
      Tags  []int
    }
    

    For example:

    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
    ", contents)
      // => []main.Content{main.Content{Title:"hi", Tags:[]int{1, 2, 3, 4, 5, 6}}}
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示