github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcodec/xjson/types.go (about)

     1  package xjson
     2  
     3  import (
     4  	bytes2 "bytes"
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  // Int64String is a go int64 type.
    10  //
    11  // which can marshal into json string, and unmarshal from json string or json number.
    12  //	type User struct {
    13  //	  UID Int64String `json:"uid"`
    14  //	}
    15  // so we can marshal into
    16  //	{"uid": "123456"}
    17  // unmarshal from both
    18  //	{"uid": 123456}
    19  // and
    20  //	{"uid": "123456"}
    21  type Int64String int64
    22  
    23  func (i Int64String) MarshalJSON() ([]byte, error) {
    24  	return []byte(fmt.Sprintf("\"%v\"", i)), nil
    25  }
    26  
    27  func (i *Int64String) UnmarshalJSON(bytes []byte) error {
    28  	if bytes2.HasPrefix(bytes, []byte{'"'}) {
    29  		bytes = bytes[1 : len(bytes)-1]
    30  	}
    31  	m, err := strconv.ParseInt(string(bytes), 10, 64)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	*i = Int64String(m)
    36  	return nil
    37  }
    38  
    39  func (i Int64String) Int64() int64 { return int64(i) }
    40  func (i Int64String) Int32() int32 { return int32(i) }
    41  func (i Int64String) Int16() int16 { return int16(i) }
    42  func (i Int64String) Int8() int8   { return int8(i) }
    43  func (i Int64String) Int() int     { return int(i) }