Rumah  >  Soal Jawab  >  teks badan

go语言读取json格式字符串问题,在线等!

package main import (

"encoding/json" "fmt" 
)

func main ( ) {

str:=`{"repositories":["heapster","mysql","zeppelin"]}`
byteStr:=[]byte(str)

type Repository struct{
    repositories []string
}
var repo Repository
json. Unmarshal ( byteStr , &repo )
fmt.Println(repo)

}

最后输出为空的数组,请问哪里错了???


高洛峰高洛峰2899 hari yang lalu1152

membalas semua(2)saya akan balas

  • 欧阳克

    欧阳克2016-11-10 11:51:16

    你这个是struct的item都是私有的,只能当前package调用,要是传给json的话,就会读取不到定义struct的时候大写首字母即可

    func main(){
    str:=`{"repositories":["heapster","mysql","zeppelin"]}`
    byteStr:=[]byte(str)
    type Repository struct{
        Repositories []string
    }
    var repo Repository
    json. Unmarshal ( byteStr , &repo )
    fmt.Println(repo) 
    }

    至于楼上说的struct加tag描述,那是为了字段名不一致使用的,默认情况下解析首字母大写会自动检测小写的,下面这种情况就需要定义tag表述

    func main(){
    str:=`{"test_repositories":["heapster","mysql","zeppelin"]}`
    byteStr:=[]byte(str)
    type Repository struct{
        Repositories []string `json:"test_repositories"`
    }
    var repo Repository
    json. Unmarshal ( byteStr , &repo )
    fmt.Println(repo) 
    }


    balas
    0
  • 三叔

    三叔2016-11-10 11:50:19

    type Repository struct{
        Repositories []string `json:"repositories"`
    }

    可导出字段才可以被反射赋值

    balas
    0
  • Batalbalas