JSON对象未解组,但没有抛出错误。

huangapple go评论82阅读模式
英文:

JSON object not unmarshalling, but not throwing errors

问题

我只返回翻译好的部分,以下是翻译的结果:

我只是尝试对这个项目进行一些基本的JSON解组,代码如下:

testJson := `{
        "Users": [
          {
                "id": 1,
                "username": "bbrewer"
          },
          {
                "id": 2,
                "username": "rsmith"
          },
          {
                "id": 3,
                "username": "jmorgan"
          },
          {
                "id": 4,
                "username": "dwallis"
          }]
        }` 

我想以这样的方式进行操作,以便我可以使用每个条目的各个组件(例如user.ID或user.UserName)。我已经设置了一个结构体,如下所示:

type UserInfo struct {
        ID              int     `json:"id"`
        UserName        string  `json:"username"`
}

然而,每当我尝试解组时,虽然不会抛出任何错误,但似乎无法正确解析它。当我尝试使用range打印时,没有任何输出,而且似乎我试图将其与之关联的对象为空。我做错了什么?
这是我的完整代码(请注意,我也尝试过不使用UserList类型,而是使用UserInfo结构体类型):

package main

import "fmt"
import "encoding/json"

type UntypedJson map[string][]interface{}

type UserInfo struct {
        ID              int     `json:"id"`
        UserName        string  `json:"username"`
}

type UserList []UserInfo

func main() {
        testJson := `{
        "Users": [
          {
                "id": 1,
                "username": "bbrewer"
          },
          {
                "id": 2,
                "username": "rsmith"
          },
          {
                "id": 3,
                "username": "jmorgan"
          },
          {
                "id": 4,
                "username": "dwallis"
          }]
        }`

        var users UserList
        json.Unmarshal([]byte(testJson), &users)
        for i, v := range users {
                fmt.Println("what do")
                fmt.Println(i)
                fmt.Println(v)
                fmt.Println(v.ID)
                fmt.Println(v.UserName)
        }
}

希望对你有帮助!

英文:

I'm just trying to do some basic JSON unmarshalling for this item:

testJson := `{
        "Users": [
          {
                "id": 1,
                "username": "bbrewer"
          },
          {
                "id": 2,
                "username": "rsmith"
          },
          {
                "id": 3,
                "username": "jmorgan"
          },
          {
                "id": 4,
                "username": "dwallis"
          }]
        }` 

I'm trying to do it in such a way that I can work with the individual components for each entry (so like user.ID or user.UserName). I've set up a struct for it like this:

type UserInfo struct {
        ID              int     `json:"id"`
        UserName        string  `json:"username"`
}

However, whenever I try to unmarshal it, while it doesn't throw any errors, it doesn't seem to be parsing it properly. When I try to print using a range, nothing is outputted, and it seems like the object I'm trying to tie it to is just empty. What am I doing wrong?
Here's my full code (note that I've also tried it without the UserList type, with users as the UserInfo struct type):

package main

import "fmt"
//import "net/http"
//import "io/ioutil"
import "encoding/json"

type UntypedJson map[string][]interface{}

type UserInfo struct {
        ID              int     `json:"id"`
        UserName        string  `json:"username"`
}

type UserList []UserInfo

func main() {
        testJson := `{
        "Users": [
          {
                "id": 1,
                "username": "bbrewer"
          },
          {
                "id": 2,
                "username": "rsmith"
          },
          {
                "id": 3,
                "username": "jmorgan"
          },
          {
                "id": 4,
                "username": "dwallis"
          }]
        }`

        var users UserList
        json.Unmarshal([]byte(testJson), &users)
        for i, v := range users {
                fmt.Println("what do")
                fmt.Println(i)
                fmt.Println(v)
                fmt.Println(v.ID)
                fmt.Println(v.UserName)
        }
}

答案1

得分: 0

你的代码显然出现了错误,并且你还没有处理它。首先像下面这样处理错误。

err := json.Unmarshal([]byte(testJson), &users)
if err != nil {
    // 在这里处理错误。
    log.Fatalln(err)
}

回答你的问题,你需要创建一个包含UserInfo数组的类型,如下所示。因为你的JSON字符串已经标注为"Users":[{}]

type UsersInfo struct {
    Users []UserInfo `json:"Users"`
}

然后将你的JSON解析为UsersInfo类型的变量引用。

var users UsersInfo
err := json.Unmarshal([]byte(testJson), &users)
if err != nil {
    log.Fatalln(err)
}

你可以在这里运行完整的代码。

英文:

your code obviously getting an error and you haven't handled it. first handle error like below.

    err := json.Unmarshal([]byte(testJson), &users)
	if err != nil {
		//handle error here.
        log.Fatalln(err)
	}

Answer to your question, you have to create a type including UserInfo array as below. Because your json string has annotated as "Users":[{}]

type UsersInfo struct {
	Users []UserInfo `json:"Users"`
}

And unmarshal your json to the UsersInfo type variable reference.

    var users UsersInfo
	err := json.Unmarshal([]byte(testJson), &users)
	if err != nil {
		log.Fatalln(err)
	}

You can run full code here.

huangapple
  • 本文由 发表于 2021年7月2日 22:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/68227145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定