1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 ) 7 8 type Screen struct { 9 Size float32 //屏幕尺寸 10 ResX, ResY int //水平和垂直分辨率 11 } 12 13 type Battery struct { 14 Capacity int //电池容量 15 } 16 17 func getJsonData() []byte { 18 raw := &struct { 19 Screen 20 Battery 21 HasTouchID bool 22 }{ 23 Screen: Screen{ 24 Size: 5.5, 25 ResX: 1920, 26 ResY: 1080, 27 }, 28 Battery: Battery{ 29 2910, 30 }, 31 HasTouchID: true, 32 } 33 jsonData, _ := json.Marshal(raw) 34 return jsonData 35 } 36 func main() { 37 jsonData := getJsonData() 38 fmt.Printf(string(jsonData)) 39 40 screenAndTouch := struct { 41 Screen 42 HasTouchID bool 43 }{} 44 45 json.Unmarshal(jsonData, &screenAndTouch) 46 fmt.Printf("%+v\n", screenAndTouch) 47 }