duanju8308 2016-01-09 17:48
浏览 40
已采纳

开始-JSON解码器未初始化我的结构

I am trying to decode some JSON retrieved via http.Get. However, when I check the structs I initialize with fmt.Println, they are always empty.

I suspect it is because my struct's structure does not agree with the returned JSON, but I am not sure how to fix it. In general, I am not exactly quite sure how the decoder works.

This is the JSON:

{
  "response":[
    {
      "list": {
        "category":"(noun)",
        "synonyms":"histrion|player|thespian|role player|performer|performing artist"
      }
    },
    {
      "list": {
        "category":"(noun)",
        "synonyms":"doer|worker|person|individual|someone|somebody|mortal|soul"
      }
    }
  ]
}

Here is what i have tried so far:

type SynonymResponse struct {
    lists []SynonymList
}

type SynonymList struct {
    category string
    synonyms string
}

var synonyms SynonymResponse;
dec := json.NewDecoder(response.Body)
err := dec.Decode(&synonyms)
if err != nil {
    log.Fatal(err)
}
fmt.Println(synonyms)

EDIT: Per @Leo's answer and @JimB's hint, there are two issues with my attempt. Below is the proper set of structs, though as Leo pointed out, this will be empty:

type SynonymResponses struct {
    resp []SynonymResponse
}

type SynonymResponse struct {
    listo SynonymList
}

type SynonymList struct {
    cat string
    syns string
} 
  • 写回答

1条回答 默认 最新

  • doyz51819 2016-01-09 17:55
    关注

    In order for your JSON to be picked up by the decoder, the fields in your struct must be exported.

    This means you need you capitalize the field names. If you have custom naming on your fields -> json conversion, you can add json tags to your structs.

    This will fix your issue:

    type SynonymResponse struct {
        Lists []SynonymList `json:"response"`
    }
    
    type SynonymList struct {
        Category string `json:"category"`
        Synonyms string `json:"synonyms"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题