1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
   | import ( 	"bytes" 	"encoding/json" 	"fmt" 	"strconv" 	"time" )
  type Person struct { 	Name string 	Util float64 }
  type StrictFloat64 float64
 
  func (f StrictFloat64) MarshalJSON() ([]byte, error) { 	if float64(f) == float64(int(f)) { 		return []byte(strconv.FormatFloat(float64(f), 'f', -1, 64)), nil  	} 	return []byte(strconv.FormatFloat(float64(f), 'f', -1, 64)), nil }
  type StrictPerson struct { 	Name string 	Util StrictFloat64 }
  func main() { 	p1 := Person{"ross", 1.01} 	p2 := Person{"jack", 1.00}  	p1Json, _ := json.Marshal(p1) 	fmt.Println("\"ross\", 1.01 --> " + string(p1Json)) 	p2Json, _ := json.Marshal(p2) 	fmt.Println("\"ross\", 1.00 --> " + string(p2Json))
  	sp1 := StrictPerson{"ross", 1.01} 	sp2 := StrictPerson{"jack", 1.00001}  	sp1Json, _ := json.Marshal(sp1) 	fmt.Println("\"ross\", 1.01 (自定义 StrictFloat64 类型)--> " + string(sp1Json)) 	sp2Json, _ := json.Marshal(sp2) 	fmt.Println("\"ross\", 1.00 (自定义 StrictFloat64 类型) --> " + string(sp2Json))
  	p_Demo := &StrictPerson{} 	json.Unmarshal(sp2Json, p_Demo) 	fmt.Printf("%#v", p_Demo) }
 
 
 
 
 
 
 
 
   |