【Go语言】解析复合json数据

1、解析复合json数据


a、第三方库,简单明快,方便实用;

package main

import (
	"fmt"
	simplejson "github.com/bitly/go-simplejson"
)

// 读取复合结构体的例子
type JData struct {
     
	Id string `json:"id"`
}

type Session struct {
     
	Janus string `json:"janus"`
	Transaction string `json:"transaction"`
	Data JData `json:"data"`

}

func main() {
     
	respBytes:= `{
		"janus": "success",
		"transaction": "VonUzjg4IVSq",
		"data": {
		"id": 4753364339368792
		}
	}`
	result, err := simplejson.NewJson([]byte(respBytes))
	if err != nil {
     
		fmt.Printf("%v\n", err)
		return
	}
	id, err := result.Get("data").Get("id").Int()
	fmt.Println(id)
}

b、标准库解析

package main

import (
	"encoding/json"
	"fmt"
)
type Point1 struct {
     
	X int `json:"x"`
	Y int `json:"y"`
}

type Circle1 struct {
     
	Point1
	Radius int `json:"radius"`
}

type Circle2 struct {
     
	Point1		`json:"point"`
	Radius int `json:"radius"`
}
func main() {
     
	data := `{"x":80,"y":60,"radius":20}`
	var c Circle1
	json.Unmarshal([]byte(data), &c)
	fmt.Println(c)
	fmt.Println("*****************************")
	data1 := `{"point":{"x":80,"y":60},"radius":20}`
	var c1 Circle2
	json.Unmarshal([]byte(data1), &c1)
	fmt.Println(c1)
}

对应结果:


{
     {
     80 60} 20}
*****************************
{
     {
     80 60} 20}

Process finished with exit code 0

注:特别注意是否对匿名字段用了“字段标签”,如果用了,那么要使用Circle2的对应解析方法,如果仅仅匿名字段,没有标签,那么使用Circle1的解析方法。

你可能感兴趣的:(Golang,go,json,golang)