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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试