golang 实现 struct、json、map 互相转化

1. golang 实现 struct、json、map 互相转化

1.1. Json 和 struct 互换

1.1.1. Json 转 struct

package main 
import (
    "fmt"
    "encoding/json"
)
  
type People struct {
    Name string `json:"name_title"`
    Age int `json:"age_size"`
}
  
func JsonToStructDemo(){
    jsonStr := `
    {
        "name_title": "jqw"
        "age_size":12
    }
    `
    var people People
    json.Unmarshal([]byte(jsonStr), &people)
    fmt.Println(people)
}
  
func main(){
    JsonToStructDemo()
}

注意 json 里面的 key 和 struct 里面的 key 要一致, struct 中的 key 的首字母必须大写, 而 json 中大小写都可以。

1.1.2. truct 转 json

在结构体中引入 tag 标签, 这样匹配的时候 json 串对应的字段名需要与 tag 标签中定义的字段名匹配, 当然 tag 中定义的名称不需要首字母大写, 且对应的 json 串中字段名仍然大小写不敏感。此时, 结构体中对应的字段名可以不用和匹配的一致, 但是首字母必须大写, 只有大写才是可对外提供访问的。

package main 
import (
    "fmt"
    "encoding/json"
)
  
type People struct {
    Name string `json:"name_title"`
    Age int `json:"age_size"`
}
  
func StructToJsonDemo(){
    p := People{
        Name: "jqw",
        Age: 18,
    }
  
    jsonBytes, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(jsonBytes))
}
  
func main(){
    StructToJsonDemo()
}

1.2. json 和 map 互转

1.2.1. json 转 map

func JsonToMapDemo(){
    jsonStr := `
    {
        "name": "jqw",
        "age": 18
    }
    `
    var mapResult map[string]interface{}
    err := json.Unmarshal([]byte(jsonStr), &mapResult)
    if err != nil {
        fmt.Println("JsonToMapDemo err:", err)
    }
    fmt.Println(mapResult)
}

1.2.2. map 转 Json

func MapToJsonDemo1(){
    mapInstances := []map[string]interface{}{}
    instance_1 := map[string]interface{}{"name": "John", "age": 10}
    instance_2 := map[string]interface{}{"name": "Alex", "age": 12}
    mapInstances = append(mapInstances, instance_1, instance_2) 
    jsonStr, err := json.Marshal(mapInstances)
  
    if err != nil {
        fmt.Println("MapToJsonDemo err:", err)
    }
    fmt.Println(string(jsonStr))
}
func MapToJsonDemo2(){
    b, _ := json.Marshal(map[string]int{"test":1, "try":2})
    fmt.Println(string(b))
}

1.3. map 和 struct 互转

1.3.1. map 转 struct

go get github.com/goinggo/mapstructure
func MapToStructDemo(){
    mapInstance := make(map[string]interface{})
    mapInstance["Name"] = "jqw"
    mapInstance["Age"] = 18
  
    var people People
    err := mapstructure.Decode(mapInstance, &people)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(people)
}

1.3.2. struct 转 map

func StructToMapDemo(obj interface{}) map[string]interface{}{
    obj1 := reflect.TypeOf(obj)
    obj2 := reflect.ValueOf(obj)
  
    var data = make(map[string]interface{})
    for i := 0; i < obj1.NumField(); i++ {
        data[obj1.Field(i).Name] = obj2.Field(i).Interface()
    }
    return data
}
func TestStructToMap(){
    student := Student{10, "jqw", 18}
    data := StructToMapDemo(student)
    fmt.Println(data)
}

2. How to pretty-print JSON with Go

Go has inside the standard library all things needed to marshal/unmarshal JSON (Marshaling is the process of transforming an object into a storable representation using a specific format).

To pretty-print JSON, you can use json.MarshalIndent :

package main

import (
   "encoding/json"
   "fmt"
   "log"
)

type Teacher struct {
   ID        string `json:"id"`
   Firstname string `json:"firstname"`
   Lastname  string `json:"lastname"`
}

func main() {
   john := Teacher{
      ID:        "678930",
      Firstname: "John",
      Lastname:  "Doe",
   }
   marshaled, err := json.MarshalIndent(john, "", "   ")
   if err != nil {
      log.Fatalf("marshaling error: %s", err)
   }
   fmt.Println(string(marshaled))
}

Parameters of json.MarshalIndent:

  • The variable that you want to marshal into JSON (encode)
  • The prefix that will be added to each JSON element => here nothing = empty string
  • The indentation that you want to apply, here we use a tab.

This program outputs :

{
        "id": "678930",
        "firstname": "John",
        "lastname": "Doe"
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云满笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值