我使用
int
键入以表示枚举。当我将其封送为JSON时,我想将其转换为字符串,AFAIK,我应该实现
UnmarshalJSON
和
MarshalJSON
,但它抱怨:
封送处理错误:json:为类型调用MarshalJSON时出错
主要的trxStatus:查找的开头字符“b”无效
值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)
}