我们用golang的json来marshal一个结构体的时候,结构体的未导出的成员将无法被json访问,也就是不会出现json编码的结果里(也就是小写的成员没法导出)

这个是由于技术的上问题引起的:golang的结构体里的成员的名字如果以小写字母开头,那么其他的包是无法访问的,也就是json无法访问我们的结构体里小写字母开头的成员


这个可以有两种方法解决

1. struct的成员用大写开头,然后加tag

2. 实现json.Marshaler接口


第一种方法比较常见这儿就不详细展开了

第二种方法如下

http://play.golang.org/p/AiTwUOWkiT

package main

import "fmt"
import "encoding/json"

func main() {
	var s S
	s.a = 5
	s.b[0] = 3.123
	s.b[1] = 111.11
	s.b[2] = 1234.123
	s.c = "hello"
	s.d[0] = 0x55

	j, _ := json.Marshal(s)
	fmt.Println(string(j))
}

type S struct {
	a int
	b [4]float32
	c string
	d [12]byte
}

func (this S) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"a": this.a,
		"b": this.b,
		"c": this.c,
		"d": this.d,
	})
}

输出:

{"a":5,"b":[3.123,111.11,1234.123,0],"c":"hello","d":[85,0,0,0,0,0,0,0,0,0,0,0]}


也就是结构体实现MarshalJSON() ([]byte, error)函数即可,在这个函数里导出你想要导出的成员就可以了。

这样就可以正常的使用json.Marshal之类的函数了


GitHub 加速计划 / js / json
19
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:5 个月前 )
34665ae6 binary -> binary_t Signed-off-by: Robert Chisholm <robert.chisholm@sheffield.ac.uk> 6 天前
f3dc4684 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.28.10. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 13 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐