序列化的内容是否严格按照定义使用encoding / json包的顺序?

问题描述:

I use encoding/jsonto serialize struct. I'm confused about the output of json.Marshal function. Does the serialized field content strictly follow the order in the struct definition?

e.g. Here is a struct definition

type MyStruct struct {
    Field1  string
    Field2  string
}

could the output be {"Field2":"field2","Field1":"field1"}? Since if the output struct fields out of order, the hash of the serialized content will be uncertain.

我使用 encoding / json code>序列化结构。 我对 json.Marshal code>函数的输出感到困惑。 序列化字段的内容是否严格遵循struct定义中的顺序? p>

例如。 这是一个结构定义 p>

 类型MyStruct结构{
 Field1字符串
 Field2字符串
} 
  code>  pre> 
 
 

输出是 {“ Field2”:“ field2”,“ Field1”:“ field1”} code>吗? 因为如果输出struct的字段混乱,则序列化内容的哈希将不确定。 p> div>

The current implementation is deterministic, e.g. for structs see https://golang.org/src/encoding/json/encode.go#L629 which gives struct order (and maps are by sorted keys).

But as this is not guaranteed by the documentation you should consider this an implementation detail.

If you want to hash the output you'll face more problems, e.g. there are several equivalent representations of characters in strings and JSON has no notion of an int (floats only). It really depends on what you try to do wirh that hash.

Does the serialized field content strictly follow the order in the struct definition?

No. There is no guarantee of this. In practice, while it may be true for many data types, such as structs, it will certainly not be true for maps, and one should never depend on the order remaining the same, as implementation details can change between Go versions or even Go compilers, and if you assume consistent ordering in such cases, you could introduce bugs.

If ordering is important for your specific data types, you can implement a custom json.Marshaler that preserves order.