(un)marshalling json在golang中不起作用

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

(un)marshalling json golang not working

问题

我正在使用Go语言进行开发,但是在使用json编码和解码时遇到了问题。

我几乎按照示例的原样复制了代码,但输出显示marshal和unmarshal都没有返回任何数据。它们也没有报错。

有人可以给我一些提示吗?

我的示例代码:Go playground

package main

import "fmt"
import "encoding/json"

type testStruct struct {
    clip string `json:"clip"`
}

func main() {
//unmarshal test
    var testJson = `{"clip":"test"}`
    var t testStruct
    var jsonData = []byte(testJson)
    err := json.Unmarshal(jsonData, &t)
    if err != nil {
        fmt.Printf("解码json时出错。错误信息:%s", err)
        return
    }
    fmt.Printf("解码后的json内容为:%#v\r\n", t)

//marshal test
    t.clip = "test2"
    data, err := json.Marshal(&t)
    if err != nil {
         fmt.Printf("编码json时出错。错误信息:%s", err)
         return
    }
    fmt.Printf("编码后的json为:%s\r\n", string(data))
}

输出结果:

 解码后的json内容为:main.testStruct{clip:""}
 编码后的json为:{}

在这两个输出中,我本来期望看到解码或编码后的json内容。

英文:

I'm playing with Go and am stumped as to why json encode and decode don't work for me

I think i copied the examples almost verbatim, but the output says both marshal and unmarshal return no data. They also don't give an error.

can anyone hint to where i'm going wrong?

my sample code: Go playground

package main

import "fmt"
import	"encoding/json"

type testStruct struct {
	clip string `json:"clip"`
}

func main() {
//unmarshal test
	var testJson = "{\"clip\":\"test\"}"
	var t testStruct
	var jsonData = []byte(testJson)
	err := json.Unmarshal(jsonData, &t)
	if err != nil {
		fmt.Printf("There was an error decoding the json. err = %s", err)
		return
	}
	fmt.Printf("contents of decoded json is: %#v\r\n", t)

//marshal test
	t.clip = "test2"
	data, err := json.Marshal(&t)
    if err != nil {
	     fmt.Printf("There was an error encoding the json. err = %s", err)
	     return
    }
 	fmt.Printf("encoded json = %s\r\n", string(data))
}

output:

 contents of decoded json is: main.testStruct{clip:""}
 encoded json = {}

in both outputs I would have expected to see the decoded or encoded json

答案1

得分: 52

例如,

package main

import "fmt"
import "encoding/json"

type testStruct struct {
    Clip string `json:"clip"`
}

func main() {
    //解码测试
    var testJson = `{"clip":"test"}`
    var t testStruct
    var jsonData = []byte(testJson)
    err := json.Unmarshal(jsonData, &t)
    if err != nil {
        fmt.Printf("解码json时发生错误。错误信息:%s", err)
        return
    }
    fmt.Printf("解码后的json内容为:%#v\r\n", t)

    //编码测试
    t.Clip = "test2"
    data, err := json.Marshal(&t)
    if err != nil {
        fmt.Printf("编码json时发生错误。错误信息:%s", err)
        return
    }
    fmt.Printf("编码后的json为:%s\r\n", string(data))
}

输出:

解码后的json内容为:main.testStruct{Clip:"test"}
编码后的json为:{"clip":"test2"}

Playground链接:

http://play.golang.org/p/3XaVougMTE

导出结构体字段。

type testStruct struct {
    Clip string `json:"clip"`
}

导出的标识符

为了允许从另一个包中访问标识符,可以将其导出。如果满足以下两个条件,则标识符被导出:

  • 标识符名称的第一个字符是一个Unicode大写字母(Unicode类别“Lu”);
  • 标识符在包块中声明,或者它是字段名或方法名。

所有其他标识符都不会被导出。

英文:

For example,

package main

import "fmt"
import "encoding/json"

type testStruct struct {
	Clip string `json:"clip"`
}

func main() {
	//unmarshal test
	var testJson = "{\"clip\":\"test\"}"
	var t testStruct
	var jsonData = []byte(testJson)
	err := json.Unmarshal(jsonData, &t)
	if err != nil {
		fmt.Printf("There was an error decoding the json. err = %s", err)
		return
	}
	fmt.Printf("contents of decoded json is: %#v\r\n", t)

	//marshal test
	t.Clip = "test2"
	data, err := json.Marshal(&t)
	if err != nil {
		fmt.Printf("There was an error encoding the json. err = %s", err)
		return
	}
	fmt.Printf("encoded json = %s\r\n", string(data))
}

Output:

contents of decoded json is: main.testStruct{Clip:"test"}
encoded json = {"clip":"test2"}

Playground:

http://play.golang.org/p/3XaVougMTE

Export the struct fields.

type testStruct struct {
    Clip string `json:"clip"`
}

> Exported identifiers
>
> An identifier may be exported to permit access to it from another
> package. An identifier is exported if both:
>
> * the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
> * the identifier is declared in the package block or it is a field name or method name.
>
> All other identifiers are not exported.

答案2

得分: 30

将结构字段的名称大写化

type testStruct struct {
    clip string `json:"clip"` // 错误。小写字母 - 其他包无法访问
}

更改为:

type testStruct struct {
    Clip string `json:"clip"`
}
英文:

Capitalize names of structure fields

type testStruct struct {
    clip string `json:"clip"` // Wrong.  Lowercase - other packages can't access it
}

Change to:

type testStruct struct {
    Clip string `json:"clip"`
}

答案3

得分: 1

在我的情况下,我的结构字段是大写的,但我仍然遇到了相同的错误。
然后我注意到我的字段的大小写不同。我必须在我的请求中使用下划线。

例如:
我的请求体是:

{
  "method": "register",
  "userInfo": {
    "fullname": "Karan",
    "email": "email@email.com",
    "password": "random"
  }
}

但是我的 Golang 结构体是:

type AuthRequest struct {
	Method   string   `json:"method,omitempty"`
	UserInfo UserInfo `json:"user_info,omitempty"`
}

我通过修改我的请求体来解决这个问题:

{
  "method": "register",
  "user_info": {
    "fullname": "Karan",
    "email": "email@email.com",
    "password": "random"
  }
}
英文:

In my case, my struct fields were capitalized but I was still getting the same error.
Then I noticed that the casing of my fields was different. I had to use underscores in my request.

For eg:
My request body was:

{
  "method": "register",
  "userInfo": {
    "fullname": "Karan",
    "email": "email@email.com",
    "password": "random"
  }
}

But my golang struct was:

type AuthRequest struct {
	Method   string   `json:"method,omitempty"`
	UserInfo UserInfo `json:"user_info,omitempty"`
}

I solved this by modifying my request body to:

{
  "method": "register",
  "user_info": {
    "fullname": "Karan",
    "email": "email@email.com",
    "password": "random"
  }
}

huangapple
  • 本文由 发表于 2014年9月1日 02:40:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/25595096.html
匿名

发表评论

匿名网友

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

确定