douxu2081 2016-02-23 22:29
浏览 169
已采纳

Golang中的JSON解析错误

I develop this code:

package main
import (
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Client struct{
    host string
    key string
    secrete string
    username string
    password string
}

type Config struct{
    Client []Client
}

func main(){
    content, err := ioutil.ReadFile("conf2.json")
    if err!=nil{
        fmt.Print("Error:",err)
    }
    var conf Config
    err=json.Unmarshal(content, &conf)
    if err!=nil{
        fmt.Print("Error:",err)
    }
    json.Unmarshal(content, &conf)
    fmt.Println(conf.Client[0].host)
}

to parse and print the first host detail from my json, that looks like this:

{ "Client" : [ {"host":"192.168.1.2"},
{"key":"abcdf"}, {"secrete":"9F6w"}, {"username":"user"}, {"password":"password"} ] }

But I got an empty string. Could someone know the reason?

  • 写回答

3条回答 默认 最新

  • dongxi8297 2016-02-24 21:21
    关注

    Here, it is the solution to my problem: package main

    import (
      "fmt"
      "io/ioutil"
      "encoding/json"
    )
    
    type Client struct {
      Host     string `json:"host"`
      Key      string `json:"apikey"`
      Secret  string `json:"secret"`
      Username string `json:"username"`
      Password string `json:"password"`
    }
    
    type Config struct {
      Client Client `json:"Client"`
    }
    
    func main(){
      jsonmsg, err := ioutil.ReadFile("conf2.json")
    
      conf := new(Config)
      err = json.Unmarshal([]byte(jsonmsg), &conf)
      if err != nil {
        fmt.Print("Error:", err)
      }
      fmt.Printf("%+v
    %+v
    %+v
    %+v
    %+v
    ", conf.Client.Host, conf.Client.Key, conf.Client.Secret, conf.Client.Username,conf.Client.Password)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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