Golang 中解析JSON的三种方式

推荐 源码巴士 826浏览

直接贴代码,总的来说,golang 解析 JSON 跟动态语言比起来还挺费劲的,目前只找到了这三种方式来解析,可能一些 Web 框架会自动帮开发处理好吧!

package main

import (
	"encoding/json"
	"fmt"

	"github.com/bitly/go-simplejson"
)

type Address struct {
	Province string `json:"province"`
	City     string `json:"city"`
	District string `json:"district"`
	Detail   string `json:"detail"`
}

type User struct {
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	Addresses []Address `json:"addresses"`
}

func main() {
	var err error
	jsonStr := []byte(`{
	"name": "A",
	"email": "a@example.com",
	"addresses": [
		{ "province": "湖南省", "city": "长沙市", "district": "芙蓉区", "detail": "街道1010" },
		{ "province": "湖南省", "city": "长沙市",  "district": "天心区", "detail": "街道1011" }
	]
}
`)

	// 第一种方式
	fmt.Println("---------------- 第一种解析JSON方式 ----------------")
	var user map[string]interface{}
	err = json.Unmarshal(jsonStr, &user)
	if err != nil {
		panic("解析失败")
	}
	fmt.Printf("名字:%s\n", user["name"].(string))
	fmt.Printf("邮箱:%s\n", user["email"].(string))
	for i, address := range user["addresses"].([]interface{}) {
		addr := address.(map[string]interface{})
		fmt.Printf("地址%d:%s-%s-%s %s\n", i, addr["province"].(string), addr["city"].(string), addr["district"].(string), addr["detail"].(string))
	}

	fmt.Println("\n---------------- 第二种解析JSON方式 ----------------")
	var user2 User
	err = json.Unmarshal(jsonStr, &user2)
	if err != nil {
		panic("解析失败")
	}
	fmt.Printf("名字:%s\n", user2.Name)
	fmt.Printf("邮箱:%s\n", user2.Email)
	for i, address := range user2.Addresses {
		fmt.Printf("地址%d:%s-%s-%s %s\n", i, address.Province, address.City, address.District, address.Detail)
	}

	fmt.Println("\n--------------- 第三种解析JSON方式 ----------------")
	// https://pkg.go.dev/github.com/bitly/go-simplejson
	var user3 *simplejson.Json
	user3, err = simplejson.NewJson(jsonStr)
	if err != nil {
		panic("解析失败")
	}

	name, _ := user3.Get("name").String()
	email, _ := user3.Get("email").String()
	fmt.Printf("名字:%s\n", name)
	fmt.Printf("邮箱:%s\n", email)

	i := 0
	for i < len(user3.Get("addresses").MustArray()) {
		address := user3.Get("addresses").GetIndex(i)
		province, _ := address.Get("province").String()
		city, _ := address.Get("city").String()
		district, _ := address.Get("district").String()
		detail, _ := address.Get("detail").String()
		fmt.Printf("地址%d:%s-%s-%s %s\n", i, province, city, district, detail)
		i++
	}
}

转载请注明:源码巴士 » Golang 中解析JSON的三种方式