注意事项
    map记得分配内存
    解析出来的int类型会变成float64类型
    注意判断不为nil后再转换类型

    1. package main
    2. import (
    3. "fmt"
    4. "encoding/json"
    5. )
    6. func main() {
    7. var m map[string]interface{} //声明变量,不分配内存
    8. m = make(map[string]interface{}) //必可不少,分配内存
    9. m["name"] = "simon"
    10. var age int = 12
    11. m["age"] = age
    12. m["addr"] = "China"
    13. print_map(m)
    14. fmt.Println()
    15. data, err:=json.Marshal(m)
    16. fmt.Println("err:", err)
    17. fmt.Println(data)
    18. fmt.Println()
    19. m1 := make(map[string]interface{})
    20. err = json.Unmarshal(data, &m1)
    21. fmt.Println("err:", err)
    22. fmt.Println(m1)
    23. print_map(m1)
    24. fmt.Println()
    25. if m1["name"]!= nil {
    26. fmt.Println(m1["name"].(string))
    27. }
    28. if m1["type"]!= nil {
    29. fmt.Println(m1["type"].(string))
    30. } else {
    31. fmt.Println("there is not the key of type")
    32. }
    33. }
    34. //解析 map[string]interface{} 数据格式
    35. func print_map(m map[string]interface{}) {
    36. for k, v := range m {
    37. switch value := v.(type) {
    38. case nil:
    39. fmt.Println(k, "is nil", "null")
    40. case string:
    41. fmt.Println(k, "is string", value)
    42. case int:
    43. fmt.Println(k, "is int", value)
    44. case float64:
    45. fmt.Println(k, "is float64", value)
    46. case []interface{}:
    47. fmt.Println(k, "is an array:")
    48. for i, u := range value {
    49. fmt.Println(i, u)
    50. }
    51. case map[string]interface{}:
    52. fmt.Println(k, "is an map:")
    53. print_map(value)
    54. default:
    55. fmt.Println(k, "is unknown type", fmt.Sprintf("%T", v))
    56. }
    57. }
    58. }