douzhuoxia0587
douzhuoxia0587
2019-04-01 18:06
浏览 127

发生错误: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
    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

    点赞 评论

相关推荐