简体   繁体   English

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

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

I'm new to golang and I'd like to get a json object into my code: 我是golang的新手,我想在我的代码中添加一个json对象:

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 json:无法将字符串解编为[] main.KVU类型的Go值。退出状态1

The json that I'm trying to import is like this: 我要导入的json是这样的:

{
  "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: 我尝试了以下Users不同类型定义:

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 json:无法将字符串解组为[] main类型的Go值。

How can I fix this? 我怎样才能解决这个问题?

The error is because you have to create Users struct rather than KUV for unmarshalling the JSON. 该错误是因为您必须创建Users结构而不是KUV才能解组JSON。 Since []KVU is a slice which will unmarshal the array of children which is an array of Objects. 因为[] KVU是一个切片,它将解组作为对象数组的children级数组。 Also you need to parse the Json returned from the server to remove escape characters like / . 另外,您还需要解析从服务器返回的Json以删除转义字符,例如/ Use strconv.Unquote to manage with escaped JSON. 使用strconv.Unquote来管理转义的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. Unquote将s解释为单引号,双引号或反引号的Go字符串文字,并返回s引用的字符串值。 (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.) (如果s用单引号引起来,它将是Go字符文字; Unquote返回相应的单字符字符串。)

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 去操场的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 json:无法将数组解组为main类型的Go值 - json: cannot unmarshal array into Go value of type main.Posts json:无法将字符串解组为main.test_struct类型的Go值 - json: cannot unmarshal string into Go value of type main.test_struct json:无法将字符串解组为 map[string]interface {} 类型的 Go 值 - json: cannot unmarshal string into Go value of type map[string]interface {} golang:解组:json:无法将数组解组为main.MonitorServerInfo类型的Go值 - golang : Unmarshal: json: cannot unmarshal array into Go value of type main.MonitorServerInfo json:无法将字符串解组为 MyMap.map 类型的 Go 值 - json: cannot unmarshal string into Go value of type MyMap.map json:无法将 object 解组为 Go 类型值 - json: cannot unmarshal object into Go value of type panic:json:无法将数组解组为main类型的Go值。 - panic: json: cannot unmarshal array into Go value of type main.Structure json:无法将字符串解组为 main.CaseReport 类型的 Go struct field.result.case_report - json: cannot unmarshal string into Go struct field .result.case_report of type main.CaseReport json:无法将数字解组为 Go 结构字段。字符串类型的数量 - json: cannot unmarshal number into Go struct field .Amount of type string Kubernetes错误json:无法将字符串解组为map [string] interface {}类型的Go值 - Kubernetes error json: cannot unmarshal string into Go value of type map[string]interface {}
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM