doujuanxun7167 2014-11-02 19:35
浏览 119

Golang解析JSON返回0

The JSON that I am at tempting to parse is very basic and looks like this.

{"id": 3, "title":"Test"}

The following is the code that I am attempting to use for creating and parsing the JSON.

package main

import (
    "fmt"
    "encoding/json"
)

type Config struct{
    id int
    title string
}

func main() {
    var jsonStr = []byte(`{"id": 3, "title":"Test"}`)
    var conf Config
    err := json.Unmarshal(jsonStr, &conf)
    if err!=nil{
            fmt.Print("Error:",err)
    }
    fmt.Println(conf)
    fmt.Println(string(jsonStr))
}

Been looking over a lot of different code examples and can't see what I'm doing wrong. When I attempt to run this, this is what I get as a return.

{0 }
{"id": 3, "title":"Test"} 

I have verified that the JSON is valid, but continue to get an empty return when attempting to use json.Unmarshal. Any ideas on what I am missing so that I can get this JSON parsed?

EDIT: Looks like I can get this to work if I capitalize the titles (Id, Title). Unfortunately the return I am testing for is a return from an API which returns everything in lowercase. I need to be able to parse this JSON with lowercase titles as listed above.

  • 写回答

2条回答 默认 最新

  • dss524049 2014-11-02 19:39
    关注

    Your Config struct's fields need to be exported (upper-case), but the keys in your JSON object may remain lower-case.

    See here: http://play.golang.org/p/0A5tkCkSO5

    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法