Kok*_*zzu 2 javascript json go json-deserialization json-serialization
是否可以修改 json 序列化和反序列化,使结构如下:
type Foo struct {
A int64
B uint64
// and other stuff with int64 and uint64 and there's a lot of struct that are like this
}
x := Foo{A: 1234567890987654, B: 987654321012345678}
byt, err := json.Marshal(x)
fmt.Println(err)
fmt.Println(string(byt))
// 9223372036854775808 9223372036854775808
err = json.Unmarshal([]byte(`{"A":"12345678901234567", "B":"98765432101234567"}`), &x)
// ^ must be quoted since javascript can't represent those values properly (2^53)
// ^ json: cannot unmarshal string into Go struct field Foo.A of type int64
fmt.Println(err)
fmt.Printf("%#v\n", x)
// main.Foo{A:1234567890987654, B:0xdb4da5f44d20b4e}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/dHN-FcJ7p-N
这样它就可以接收 json 字符串,但解析为 int64/uint64,并且可以将 int64/uint64 反序列化为 json 字符串,而无需修改 struct 或 struct 标记
使用JSON 结构标记中的string选项。它是专门为这个用例而设计的:
“string”选项表示字段以 JSON 形式存储在 JSON 编码的字符串中。它仅适用于字符串、浮点、整数或布尔类型的字段。与 JavaScript 程序通信时有时会使用这种额外的编码级别
type Foo struct {
A int64 `json:"A,string"`
B uint64 `json:"B,string"`
}
func main() {
x := &Foo{}
_ = json.Unmarshal([]byte(`{"A":"12345678901234567", "B":"98765432101234567"}`), x)
fmt.Println(x) // &{12345678901234567 98765432101234567}
b, _ := json.Marshal(x)
fmt.Println(string(b)) // {"A":"12345678901234567","B":"98765432101234567"}
}
Run Code Online (Sandbox Code Playgroud)
游乐场:https://play.golang.org/p/IfpcYOlcKMo
如果您无法修改现有的结构标记(但您的示例没有),那么您必须string在自定义UnmarshalJSON和MarshalJSON 方法中重新发明此标记选项的实现。