camulos king
camulos king

Reputation: 41

golang json.Unmarshal to struct []byte

type TTT struct {
    Info []byte
    Version int32
}
func main(){
    info:=`{"info":"0x97e302078c11ca8e7d75e2eedd1091eafec353864212085406d8d7dca0e3fa4a","version":20}`
    test:=TTT{}
    err:=json.Unmarshal([]byte(info),&test)
    if err != nil {
        fmt.Println("Error in JSON unmarshalling from json marshalled object:", err)
        return
    }
    fmt.Println((test))
}

ERRROR:Error in JSON unmarshalling from json marshalled object: illegal base64 data at input byte 64

Upvotes: 2

Views: 6388

Answers (2)

M Rostami
M Rostami

Reputation: 4195

You probably need to encode your hex data:

package main

import (
        "encoding/base64"
        "encoding/json"
        "fmt"
)

type TTT struct {
        Info    []byte
        Version int32
}

func main() {
        b64Content := base64.StdEncoding.EncodeToString([]byte("0x97e302078c11ca8e7d75e2eedd1091eafec353864212085406d8d7dca0e3fa4a"))
        info := fmt.Sprintf(`{"info":"%s","version":20}`, b64Content)
        test := TTT{}
        err := json.Unmarshal([]byte(info), &test)
        if err != nil {
                fmt.Println("Error in JSON unmarshalling from json marshalled object:", err)
                return
        }
        fmt.Printf("%s", test.Info)
}

Upvotes: 3

johnson
johnson

Reputation: 388

The default json parser will parse []byte from base64 string.

If your source string is not base64, then you'll need to define your own marshaler.

type TTT struct {
    Info    bytes
    Version int32
}

type bytes []byte

func (b *bytes) MarshalJSON() ([]byte, error) {
    str := string(input)
    bs, err :=hex.DecodeString(str[3:len(str)-1])
    if err!=nil{
        return err
    }
    *b = bs
    return nil
}

func (b *bytes) UnmarshalJSON(input []byte) error {
    *b = bytes(input)
    return nil
}

func main() {
    info := `{"info":"0x97e302078c11ca8e7d75e2eedd1091eafec353864212085406d8d7dca0e3fa4a","version":20}`
    test := TTT{}
    err := json.Unmarshal([]byte(info), &test)
    if err != nil {
        fmt.Println("Error in JSON unmarshalling from json marshalled object:", err)
        return
    }
    fmt.Println((test))
}

Upvotes: 2

Related Questions