Marshal / Unmarshal int类型

时间:2018-05-05 08:22:20

标签: json go marshalling

我使用int类型来表示枚举。当我将它编组为JSON,AFAIK时,我想将它转换为字符串,我应该实现UnmarshalJSONMarshalJSON,但它会抱怨:

  

marshal error:json:错误调用MarshalJSON的类型   main.trxStatus:无效字符'b'正在寻找开头   valueunexpected JSON输入结束

编组时。然后我将引号添加到编组字符串:

func (s trxStatus) MarshalJSON() ([]byte, error) {
    return []byte("\"" + s.String() + "\""), nil
}

Marshal现在正常工作,但它无法正确地从编组字节流中Unmarshal

package main

import (
    "encoding/json"
    "fmt"
)

type trxStatus int

type test struct {
    S trxStatus
    A string
}

const (
    buySubmitted trxStatus = iota
    buyFilled
    sellSubmiited
    sellFilled
    finished
)

var ss = [...]string{"buySubmitted", "buyFilled", "sellSubmiited", "sellFilled", "Finished"}

func (s *trxStatus) UnmarshalJSON(bytes []byte) error {
    status := string(bytes)
    // unknown
    for i, v := range ss {
        if v == status {
            tttt := trxStatus(i)
            *s = tttt
            break
        }
    }
    return nil
}

func (s trxStatus) MarshalJSON() ([]byte, error) {
    return []byte(s.String()), nil
}

func (s trxStatus) String() string {

    if s < buySubmitted || s > finished {
        return "Unknown"
    }

    return ss[s]
}

func main() {
    s := test{S: buyFilled, A: "hello"}
    j, err := json.Marshal(s)
    if err != nil {
        fmt.Printf("marshal error: %v", err)
    }
    var tt test
    fmt.Println(json.Unmarshal(j, &tt))
    fmt.Println(tt)
}

1 个答案:

答案 0 :(得分:1)

编写自定义Marshaler和Unmarshaler实现时,请确保包含或修剪json字符串的周围双引号。

func (s *trxStatus) UnmarshalJSON(bytes []byte) error {
    status := string(bytes)
    if n := len(status); n > 1 && status[0] == '"' && status[n-1] == '"' {
        status = status[1:n-1] // trim surrounding quotes
    }
    // unknown
    for i, v := range ss {
        if v == status {
            tttt := trxStatus(i)
            *s = tttt
            break
        }
    }
    return nil
}

func (s trxStatus) MarshalJSON() ([]byte, error) {
    return []byte(`"` + s.String() + `"`), nil
}