gpt4 book ai didi

json - 出现错误 : math/big: cannot unmarshal into a *big. Int

转载 作者:IT王子 更新时间:2023-10-29 00:47:45 30 4
gpt4 key购买 nike

我正在尝试将 json 字符串解码为 golang 中的大整数。我收到以下错误。还有另一种方法可以使它起作用吗?

There was an error: math/big: cannot unmarshal "\"82794247871852158897004947856472973914188862150580220767211643167985440428259\"" into a *big.Int

代码:

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

package main

import (
"fmt"
"math/big"
"encoding/json"
)


type Signature struct {
R, S *big.Int
V, O uint8 // V is a reconstruction flag and O a multi sig order
}


func main() {

string := []byte(`{"O":0,"R":"82794247871852158897004947856472973914188862150580220767211643167985440428259","S":"39475619887140601172207943363731402979187092853596849493781395367115389948109","V":0}`)

var sig Signature

err2 := json.Unmarshal([]byte(string), &sig)
if err2 != nil {
fmt.Println("There was an error:", err2)
}
fmt.Println("r", sig.R, "s", sig.S, "o", sig.O, "v", sig.V)

}

最佳答案

@d3t0x!请看

big#Int.SetString

可能的方式:

package main

import (
"encoding/json"
"fmt"
"math/big"
)

type Signature struct {
R, S BigInt
V, O uint8 // V is a reconstruction flag and O a multi sig order
}

type BigInt struct {
big.Int
}

func (i *BigInt) UnmarshalJSON(b []byte) error {
var val string
err := json.Unmarshal(b, &val)
if err != nil {
return err
}

i.SetString(val, 10)

return nil
}

func main() {
string := []byte(`{"O":0,"R":"82794247871852158897004947856472973914188862150580220767211643167985440428259","S":"39475619887140601172207943363731402979187092853596849493781395367115389948109","V":0}`)

var sig Signature

err2 := json.Unmarshal([]byte(string), &sig)
if err2 != nil {
fmt.Println("There was an error:", err2)
}

fmt.Printf("r %s s %s o %d v %d", sig.R.String(), sig.S.String(), sig.O, sig.V)
}

Playground :

1) https://play.golang.org/p/Qp-hiiPDfZM

2) 草稿而不是干净的解决方案 https://play.golang.org/p/YYdf85ub5-T

关于json - 出现错误 : math/big: cannot unmarshal into a *big. Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55461131/

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