简体   繁体   English

无法将 JSON 字符串解组为 Go 中的结构

[英]Cannot Unmarshal JSON String to struct in Go

I have a string in my Go module which is the body of a HTTP response.我的 Go 模块中有一个字符串,它是 HTTP 响应的主体。 it looks something like this:它看起来像这样:

bodyString = `{"firstname": "foo", "lastname": "bar", "username": "foobar"}`

I want to convert it to the following Go struct:我想将其转换为以下 Go 结构:

type Params struct {
  FirstName string
  LastName string
  Username string
  PasswordHash string 
  EmailAddress string
}

I attempt to do so using the following:我尝试使用以下方法这样做:

var jsonMap map[string]interface{}
json.Unmarshal([]byte(bodyString), &jsonMap)

paramsIn.FirstName = jsonMap["firstname"].(string)
paramsIn.LastName = jsonMap["lastname"].(string)
paramsIn.Username = jsonMap["username"].(string)
paramsIn.PasswordHash = jsonMap["passwordhash"].(string)
paramsIn.EmailAddress = jsonMap["emailaddress"].(string)

However the unmarshal fails to match the data in the string to the appropriate keys.但是,解组无法将字符串中的数据与适当的键匹配。 ie what is stored in the jsonMap variable is only empty strings.即 jsonMap 变量中存储的只是空字符串。

I clearly am doing something wrong and I haven't worked with json in Go very much.我显然做错了,我没有在 Go 中使用 json 非常多。 If any one can help or show me the correct way to unmarshal json data from a string that would be great, thanks.如果有人可以帮助或向我展示从一个很棒的字符串中解组 json 数据的正确方法,谢谢。

Golang will convert your struct's field name ( CammelCase ) to snake_case (default). Golang 会将您的结构的字段名称( CammelCase )转换为snake_case (默认)。 So, if you have struct like:所以,如果你有这样的结构:

type Params struct {
  FirstName string
  LastName string
  Username string
  PasswordHash string 
  EmailAddress string
}

The JSON from the struct will be:结构中的 JSON 将是:

{
    "first_name":"bla",
    "last_name":"bla",
    "user_name":"bla",
    "password_hash":"ewedsads",
    "email_address":"bla@gmail.com"
}

But you can customize the JSON field name by json tag, example:但是您可以通过json标签自定义 JSON 字段名称,例如:

type Params struct {
  FirstName string `json:"firstname"`
  LastName string `json:"lastname"`
  Username string `json:"username"`
  PasswordHash string `json:"passwordhash"`
  EmailAddress string `json:"emailaddress"`
}

Then you can change your code like this:然后你可以像这样改变你的代码:

package main

import (
    "encoding/json"
    "fmt"
)

type Params struct {
    FirstName    string `json:"firstname"`
    LastName     string `json:"lastname"`
    Username     string `json:"username"`
    PasswordHash string `json:"passwordhash"`
    EmailAddress string `json:"emailaddress"`
}

func main() {
    paramsIn := Params{}
    bodyString := `{"firstname": "foo", "lastname": "bar", "username": "foobar"}`

    json.Unmarshal([]byte(bodyString), &paramsIn)
    fmt.Println(paramsIn)
}

Use go tag like this:像这样使用 go 标签:

    type Params struct {
        FirstName    string `json:"firstname"`
        LastName     string `json:"lastname"`
        Username     string `json:"username"`
        PasswordHash string
        EmailAddress string
    }

This may not be the solution to everyone who is experience this problem, and you should check out the other answers on this post and other similar SO posts.这可能不是每个遇到此问题的人的解决方案,您应该查看此帖子和其他类似 SO 帖子中的其他答案。

For me the issue was how the double quote character was being treated ( " ). My json string was being created from the body of a http response, which was being fed by a curl command in another terminal window. I was writing my curl commands in MacOS's standard text editor but I was in RTF (Rich Text Format) which formatted my " character as something else ( ) (The difference is miniscule but it was enough to completely stump me for hours.). For me the issue was how the double quote character was being treated ( " ). My json string was being created from the body of a http response, which was being fed by a curl command in another terminal window. I was writing my curl commands在 MacOS 的标准文本编辑器中,但我使用的是 RTF(富文本格式),它将我的"字符格式化为其他东西( )(差异很小,但足以让我完全难倒我几个小时。)。 There is no issue with the code above once I used the proper double quote character in the http request body.一旦我在 http 请求正文中使用了正确的双引号字符,上面的代码就没有问题了。

If I am unclear, please comment and I can clarify more.如果我不清楚,请发表评论,我可以澄清更多。

暂无
暂无

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

相关问题 json:无法将数字解组为 Go 结构字段。字符串类型的数量 - json: cannot unmarshal number into Go struct field .Amount of type string 无法将字符串解组到Go结构字段中 - cannot unmarshal string into Go struct field 松露测试:ProviderError: json: cannot unmarshal number into Go struct field params.fromBlock of type string - Truffle test: ProviderError: json: cannot unmarshal number into Go struct field params.fromBlock of type string json:无法将字符串解组为main.test_struct类型的Go值 - json: cannot unmarshal string into Go value of type main.test_struct json:无法将字符串解组为 main.CaseReport 类型的 Go struct field.result.case_report - json: cannot unmarshal string into Go struct field .result.case_report of type main.CaseReport Docker:b'json:无法将数字解组为Go结构字段LogConfig.Config,类型为string' - Docker: b'json: cannot unmarshal number into Go struct field LogConfig.Config of type string' 将json数组解组到go struct中(数组位于JSON字符串的中间 - unmarshal json array into go struct (array is in the middle of the JSON string 如何在Go中的结构中以JSON解组结构列表中的结构? - How to JSON unmarshal a struct in a list in a struct in Go? json:无法将字符串解组为 map[string]interface {} 类型的 Go 值 - json: cannot unmarshal string into Go value of type map[string]interface {} 使用运行命令执行 SSM 文档失败 json:无法将数组解组为 Go 结构字段 RunScriptPluginInput.RunCommand 类型为 string\" - SSM document execution using run command failed json: cannot unmarshal array into Go struct field RunScriptPluginInput.RunCommand of type string\"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM