dongyingdao8867 2018-07-23 12:20
浏览 38
已采纳

json:无法将字符串解组为[] main.KVU类型的Go值

I'm new to golang and I'd like to get a json object into my code:

func getUserRandking() []KVU {    
    url := "http://127.0.0.1:8080/users"

    spaceClient := http.Client{         Timeout: time.Second * 10, 
    }

    req, err := http.NewRequest(http.MethodGet, url, nil)
    if err != nil {
        log.Fatal(err)
    }

    req.Header.Set("User-Agent", "spacecount-tutorial")

    res, getErr := spaceClient.Do(req)
    if getErr != nil {
        log.Fatal(getErr)
    }

    body, readErr := ioutil.ReadAll(res.Body)
    if readErr != nil {
        log.Fatal(readErr)
    }

    var users1 []KVU
    jsonErr := json.Unmarshal(body, &users1)
    if jsonErr != nil {
        log.Fatal(jsonErr)
    }

    fmt.Println(users1)

    return users1

}

but I get this runtime error

json: cannot unmarshal string into Go value of type []main.KVU exit status 1

The json that I'm trying to import is like this:

{
  "name": "userslist",
  "children": [
    {
      "name": "cat",
      "value": 1,
      "url": "http://example.com/1.jpg"
    },
    {
      "name": "dog",
      "value": 2,
      "url": "http://example.com/2.jpg"
    }
  ]
}

I have tried different type definitions like Users below:

type KVU struct {
    Key   string `json:"name"`
    Value int    `json:"value"`
    Url   string `json:"url"`
}

type Users struct {
    Name     string `json:"name"`
    Children []KVU  `json:"children"`
}

But that also leads to:

json: cannot unmarshal string into Go value of type []main.Users

How can I fix this?

  • 写回答

1条回答 默认 最新

  • douzhanglun4482 2018-07-23 12:27
    关注

    The error is because you have to create Users struct rather than KUV for unmarshalling the JSON. Since []KVU is a slice which will unmarshal the array of children which is an array of Objects. Also you need to parse the Json returned from the server to remove escape characters like /. Use strconv.Unquote to manage with escaped JSON.

    func Unquote(s string) (string, error)
    

    Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)

    Check below working Code:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "strconv"
    )
    
    type KVU struct {
        Key   string `json:"name"`
        Value int    `json:"value"`
        Url   string `json:"url"`
    }
    
    type Users struct {
        Name     string `json:"name"`
        Children []KVU  `json:"children"`
    }
    
    func main() {
        result := getUserRandking()
        fmt.Println(result)
    }
    
    func getUserRandking() []KVU{
        input := `"{\"name\":\"userslist\",\"children\":[{\"name\":\"kachalmooferfer\",\"value\":444,\"url\":\"http://pbs.twimg.com/p‌​rofile_images/989898400609992704/UE8HiRVx_normal.jpg\"},{\"name\":\"patrick_jane7‌​7\",\"value\":407,\"url\":\"http://pbs.twimg.com/profile_images/94467727094959308‌​9/zv62U1ch_normal.jpg\"},{\"name\":\"Pensylvani\",\"value\":213,\"url\":\"http://‌​pbs.twimg.com/profile_images/1018010357892198400/Rw06UWvY_normal.jpg\"}]}"`
        var val []byte = []byte(input)
        jsonInput, err := strconv.Unquote(string(val))
        if err !=nil{
            fmt.Println(err)
        }
        var resp Users
        json.Unmarshal([]byte(jsonInput), &resp)
        // Return below struct slice for Children from the function 
        return resp.Children
    }
    

    Go Playground Example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算