Marshal

func Marshal(v interface{})([]byte, error)

  

Marshal returns the JSON encoding of v.

Marshal返回v的JSON编码。

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON.

Marshal递归地遍历值v。如果遇到的值实现了Marshaler接口并且不是一个nil指针,Marshal就会调用它的MarshalJSON方法来生成JSON。如果没有MarshalJSON方法,但该值实现了encoding.TextMarshaler,Marshal就会调用它的MarshalText方法,并将结果编码为JSON字符串。严格来说,nil指针异常并不是必要的,而是模仿了UnmarshalJSON行为中类似的必要异常。

Otherwise, Marshal uses the following type-dependent default encodings:

否则,Marshal使用以下类型相关的默认编码。

Boolean values encode as JSON booleans.

布尔值以JSON布尔值的形式编码。

Floating point, integer, and Number values encode as JSON numbers.

浮点、整数和Number值编码为JSON数字。

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).

字符串值编码为JSON字符串并被胁迫为有效的UTF-8,用Unicode替换符替换无效的字节。为了使JSON能够安全地嵌入到HTML <脚本>标签中,字符串应该使用HTMLEscape进行编码,将"<"、">"、"&"、U+2028和U+2029替换为"\u003c"、"\u003e"、"\u0026"、"\u2028 "和"\u2029"。当使用编码器时,可以通过调用SetEscapeHTML(false)来禁止这种替换。

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

数组和切片值编码为JSON数组,除了[]byte编码为base64编码的字符串,nil切片编码为空JSON值。

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

Struct值编码为JSON对象。每个导出的结构体字段都会成为JSON对象的成员k:v,使用字段名作为对象的KEY,除非该字段因下面给出的原因之一被省略。

The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

每个结构体字段的编码可以通过存储在结构体字段(field)标签(tag)中 "json "键下的格式字符串来定制。格式字符串给出了字段的名称,后面可能是一个逗号分隔的选项列表。为了在不覆盖默认字段名的情况下指定选项,名称可以为空。

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

omitempty "选项指定,如果字段的值为空,则应从编码中省略,定义为false、0、nil指针、nil接口值,以及任何空数组、片、映射或字符串。

As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".

作为一种特殊情况,如果字段标签是"-",字段总是被省略。请注意,字段的名称在JSON中为"-"的字段标签仍可使用标签"-,"生成,这种带选项的。

Examples of struct field tags and their meanings:

结构字段标签的示例及其含义。

// Field appears in JSON as key "myName".  
//字段在JSON中以 "myName "键出现
Field int `json:"myName"` // Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
//字段在JSON中以键 "myName "的形式出现,如果其值为空,则该字段从对象中省略,如上文所定义
Field int `json:"myName,omitempty"` // Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
//字段在JSON中作为键 "Field"(默认)出现,但如果为空,则跳过该字段。注意前面的逗号
Field int `json:",omitempty"` // Field is ignored by this package.
//这个包忽略了这个字段
Field int `json:"-"` // Field appears in JSON as key "-".
//字段在JSON中以"-"键出现
Field int `json:"-,"`

  

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

"string "选项标志着一个字段以JSON的形式存储在一个JSON编码的字符串中,它只适用于字符串、浮点、整数或布尔类型的字段。它只适用于字符串、浮点、整数或布尔类型的字段。这种额外的编码级别有时在与JavaScript程序通信时使用。

Int64String int64 `json:",string"`

  

The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma.

如果键名是一个非空字符串,除了引号、反斜杠和逗号之外,只包含Unicode字母、数字和ASCII标点符号,那么就会被使用。

Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

匿名结构字段通常被当作其内部导出的字段在外部结构中的字段来进行调集,但要遵守下一段中所描述的通常的Go可见性规则。一个匿名结构体字段如果在它的JSON标签中给出了一个名字,那么它将被视为拥有该名字,而不是匿名。一个接口类型的匿名结构体字段被视为具有该类型的名称,而不是匿名的。

The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:

在决定对哪个字段进行整合或取消整合时,对JSON结构字段的Go可见性规则进行了修正。如果同一层次有多个字段,而且该层次是最小的嵌套层次(因此是通常的Go规则所选择的嵌套层次),则适用以下额外规则。

1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.

在这些字段中,如果有任何字段是JSON标记的,则只考虑标记的字段,即使有多个未标记的字段,否则会发生冲突

2) If there is exactly one field (tagged or not according to the first rule), that is selected.

如果只有一个字段(无论是否根据第一条规则被标记),该字段被选中。

3) Otherwise there are multiple fields, and all are ignored; no error occurs.

否则有多个字段,都会被忽略,不会出现错误。

Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-".

匿名结构体字段的处理是 Go 1.1 中的新内容。在 Go 1.1 之前,匿名结构字段是被忽略的。要在当前和早期版本中强制忽略匿名结构字段,请给字段一个JSON标签"-"。

Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:

Map值编码为JSON对象。Map的键类型必须是字符串、整数类型或实现 encoding.TextMarshaler。通过应用以下规则对Map键进行排序,并将其作为JSON对象键使用,但须遵守上面为字符串值描述的UTF-8胁迫。

- keys of any string type are used directly

- 任何字符串类型的键都可以直接使用

- encoding.TextMarshalers are marshaled
- 编码.TextMarshalers是被调集的。
- integer keys are converted to strings
- 整数键被转换为字符串

  

Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value.

指针值编码为所指向的值。nil指针编码为空JSON值。

Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

接口值编码为接口中包含的值。无接口值编码为空JSON值。

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

通道、复数和函数值不能用JSON编码。试图对这样的值进行编码会导致Marshal返回一个UnsupportedTypeError。

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

JSON不能表示循环数据结构,Marshal不能处理它们。将循环结构传递给Marshal会导致错误。

Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

Unmarshal解析JSON编码的数据,并将结果存储在v指向的值中,如果v为nil或不是指针,Unmarshal将返回一个InvalidUnmarshalError。

Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary, with the following additional rules:
Unmarshal使用与Marshal使用的编码相反的编码,根据需要分配Map、切片和指针,附加规则如下。

To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.
要将JSON反序列化成一个指针,Unmarshal首先要处理JSON是JSON文字空的情况。在这种情况下,Unmarshal会将指针设置为nil。否则,Unmarshal会将JSON反序列化为指针指向的值。如果指针为nil,Unmarshal为其分配一个新的值。

To unmarshal JSON into a value implementing the Unmarshaler interface, Unmarshal calls that value's UnmarshalJSON method, including when the input is a JSON null. Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls that value's UnmarshalText method with the unquoted form of the string.
要将JSON反序列化到一个实现Unmarshaler接口的值中,Unmarshal调用该值的UnmarshalJSON方法,包括当输入是JSON null时。否则,如果值实现了encoding.TextUnmarshaler,并且输入是JSON引号的字符串,Unmarshal就用字符串的未引号形式调用该值的UnmarshalText方法。

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).
为了将JSON反序列化成结构体,Unmarshal将传入的JSON对象键与Marshal使用的键(结构体字段名或它的标签)进行匹配,喜欢完全匹配,但也接受不区分大小写的匹配。默认情况下,没有对应的结构体字段的对象键会被忽略(参见Decoder.DisallowUnknownFields获取替代方案)。

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

要将JSON解读成一个接口值,Unmarshal会在接口值中存储其中一个。

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
要将一个JSON数组反序列化化为一个切片,Unmarshal将切片长度重置为零,然后将每个元素追加到切片中。作为一种特殊情况,如果要将一个空的JSON数组反序列化为一个切片,Unmarshal会用一个新的空切片来替换这个分片。

To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array elements into corresponding Go array elements. If the Go array is smaller than the JSON array, the additional JSON array elements are discarded. If the JSON array is smaller than the Go array, the additional Go array elements are set to zero values.
要将JSON数组反序列化为Go数组,Unmarshal将JSON数组元素解码为相应的Go数组元素。如果Go数组小于JSON数组,那么额外的JSON数组元素将被丢弃。如果JSON数组小于Go数组,则额外的Go数组元素被设置为零值。

To unmarshal a JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map's key type must either be any string type, an integer, implement json.Unmarshaler, or implement encoding.TextUnmarshaler.
要将一个JSON对象反序列化成Map,Unmarshal首先要建立一个要使用的Map。如果Map是nil,Unmarshal会分配一个新的Map。否则,Unmarshal会重新使用现有的Map,保留现有的条目。然后Unmarshal将JSON对象中的键值对存储到map中。Map的键类型必须是任何字符串类型、整数、实现json.Unmarshaler或实现encoding.TextUnmarshaler。

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.
如果一个JSON值不适合给定的目标类型,或者一个JSON数超出了目标类型,Unmarshal就会跳过该字段,并尽可能地完成反序列化。如果没有遇到更严重的错误,Unmarshal会返回一个UnmarshalTypeError,描述最早的这种错误。在任何情况下,都不能保证在有问题的字段之后的所有剩余字段都会被反序列化到目标对象中。

The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error.
JSON null值通过将该Go值设置为nil,从而反序列化到接口、映射、指针或切片中。因为在JSON中,null经常被用来表示 "不存在",所以将JSON空值解列到任何其他Go类型中,对该值没有影响,也不会产生错误。

When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
当反序列化引号字符串时,无效的UTF-8或无效的UTF-16代理对不会被视为错误,而会被U+FFFD替换为Unicode替换字符。相反,它们会被Unicode替换字符U+FFFD取代。

json包中的Marshal&Unmarshal 文档译本的更多相关文章

  1. Elasticsearch中最重要的文档CRUD要牢记

    Elasticsearch文档CRUD要牢记 转载参考:https://juejin.im/post/5ddbf298e51d4523053c42e7 在Elasticsearch中,文档(docum ...

  2. Springboot中整合knife4j接口文档

    在项目开发过程中,web项目的前后端分离开发,APP开发,需要由前端后端工程师共同定义接口,编写接口文档,之后大家都根据这个接口文档进行开发. 什么是knife4j 简单说knife4j就swagge ...

  3. 关于.Net 7.0 RC gRPC JSON 转码为 Swagger/OpenAPI文档的注意事项

    大家好,我是失业在家,正在找工作的博主Jerry,找工作之余,看到.Net 7.0 RC2发布了,就想测试下.Net 7.0 RC2 gRPC JSON 转码为 Swagger/OpenAPI文档的特 ...

  4. 如何在ASP.NET Core 中快速构建PDF文档

    比如我们需要ASP.NET Core 中需要通过PDF来进行某些简单的报表开发,随着这并不难,但还是会手忙脚乱的去搜索一些资料,那么恭喜您,这篇帖子会帮助到您,我们就不会再去浪费一些宝贵的时间. 在本 ...

  5. 在我的电脑中删除wps云文档图标

    在我的电脑中删除wps云文档图标 右键点击win10左下角选择运行,输入regedit打开注册表后,找到以下注册表路径: HKEY_CURRENT_USER\Software\Microsoft\Wi ...

  6. 在Winform界面中实现对多文档窗体的参数传值

    在Winform界面中窗体我们一般使用多文档进行展示,也就是类似一般的选项卡的方式可以加载多个窗体界面.一般来说,我们如果打开新的窗体,给窗体传递参数是很容易的事情,但是在框架层面,一般的窗体是通过动 ...

  7. 分享一个集成在项目中的REST APIs文档框架swagger

    1 为什么是使用swagger? 1-1 当后台开发人员开发好接口,是不是还要重新书写一份接口文档提给前端人员,当然对于程序员最不喜欢的就是书写文档(当然文档是必须的,有利于项目的维护) 1-2 当后 ...

  8. spring的jar包以及相关的API文档的下载方式

    转自:http://blog.csdn.net/yuexianchang/article/details/53583327 侵删 感谢原创 首先是进入官网:https://spring.io/ 如图所 ...

  9. Java中几种office文档转pdf的方式

    最近公司要做office的文档,搜集了几种office文档转pdf的方式,简单的做下总结 我主要尝试了三种方式:openoffice,aspose,jacob 对他们进行了大文件,小文件,在linux ...

随机推荐

  1. RHCE_DAY02

    常用数值运算方式 $[] #四则运算(+ - * / % 取余数) $(()) #数值运算工具 expr #数值运算工具 let #数值运算工具 [root@localhost ~]# echo $[ ...

  2. Android全新UI编程 - Jetpack Compose 超详细教程

    1. 简介 Jetpack Compose是在2019Google i/O大会上发布的新的库.Compose库是用响应式编程的方式对View进行构建,可以用更少更直观的代码,更强大的功能,能提高开发速 ...

  3. Window2016 安装Docker

    测试环境 Windows2016 DataCenter 安装步骤 1.开始运行"PowerShell" 2.指定Tls协议为1.2.(建议都先执行这一条命令,官方文档没有这一步,实 ...

  4. Java代码搭建Dubbo+ZooKeeper 的示例

    .personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...

  5. Notes about multiboot usb creator

    U盘上的多系统启动工具,Windows上YUMI比较好,Ubuntu上MultiSystem用法复杂,unetbootin是另外一款,需要安装p7zip(apt-get install p7zip-f ...

  6. mingw+gcc 10.1下载

    链接: https://pan.baidu.com/s/1Qyqv1PDppRJvgph9sBmwxw 提取码: fqkp

  7. Python之简单的神经网络

    from sklearn import datasets from sklearn import preprocessing from sklearn.model_selection import t ...

  8. windows和liunx下换行符问题

    区别 windows换行符是: \r\n liunx换行符是: \n 问题 程序处理的时候就会有问题,因为在Windows的文件多了一个\r 解决办法(转换文件格式) vim file :set fi ...

  9. 关于PLSQL中的一些问题总结:在PLSQL中书写DDL等

    关于问题前导,使用的数据表中涉及到的字段和类型: 在PLSQL中create.drop.truncate等DDL是没有办法直接执行的. 必须要使用: Execute immediate 'DDL语句' ...

  10. 关于对String中intern方法的理解

    在java的String中有个一直被我们忽视了的方法intern方法:它的官方解释是:一个初始时为空的字符串池,它由类 String 私有地维护. 当调用 intern 方法时,如果池已经包含一个等于 ...