douzhuoxia0587 2019-04-01 18:06
浏览 186
已采纳

发生错误:math / big:无法解组为* big.Int

I am trying to unmarshal a json string into a big int in golang. I get the following error. Is there another way to get this to work?

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

Code:

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)

}
  • 写回答

1条回答 默认 最新

  • dsux90368 2019-04-01 21:08
    关注

    @d3t0x! Please, look at the

    big#Int.SetString

    Possible way:

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

    Playgrounds:

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

    2) draft and not so clean solution here https://play.golang.org/p/YYdf85ub5-T

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面