gpt4 book ai didi

javascript - 从/到 Javascript 字符串从 Go int64/uint64 序列化反序列化

转载 作者:行者123 更新时间:2023-12-01 23:16:04 27 4
gpt4 key购买 nike

是否可以修改 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}

https://play.golang.org/p/dHN-FcJ7p-N

因此它可以接收 json 字符串但解析为 int64/uint64,并且可以将 int64/uint64 反序列化为 json 字符串,而无需修改 struct 或 struct 标签

最佳答案

在 JSON 结构标签中使用 string option。它专为这种用例而设计:

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

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"}
}

Playground :https://play.golang.org/p/IfpcYOlcKMo

如果您不能修改现有的结构标签(但您的示例没有),那么您必须在自定义 UnmarshalJSON 中重新发明此 string 标签选项的实现和 MarshalJSON 方法。

关于javascript - 从/到 Javascript 字符串从 Go int64/uint64 序列化反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68852672/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com