1. 博客/

Golang自定义json解析类型的实现

·174 字·1 分钟
Go

1.json解析到Struct类型

package main

import (
	"encoding/json"
	"fmt"
)

type Book struct {
	BookName   string `json:"bookname"`
	AuthorName string `json:"authorname"`
	AuthorAge  string `json:"authorage"`
}

func main() {

	jsonbuf := `
	{
		"bookname":"booker",
		"authorname": "Tom",
		"authorage": "28"
	}`

	var book Book
	err := json.Unmarshal([]byte(jsonbuf), &book)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("book = %+v\n", book)
  // book = {BookName:booker AuthorName:Tom AuthorAge:28}
}

2.json解析到自定义类型

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

encoding/json包中定义了Unmarshaler接口,默认UnmarshalJSON方法是对要解析的json数据不做任何处理。所以要解析json数据到自定义类型,此类型需实现Unmarshaler接口。

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strings"
)

type Book struct {
	BookName string `json:"bookname"`
	Author   Author `json:"author"`
}

type Author struct {
	Name string
	Age  string
}

// Author结构体实现json.Unmarshaler接口,解析json数据时执行其UnmarshalJSON方法
func (a *Author) UnmarshalJSON(data []byte) (err error) {
	str := string(bytes.Trim(data, `" `))                   // 删除要解析的data中的"和空格
	split := strings.Split(str, ":")
	if len(split) != 2 {
		return err
	}
	a.Name = split[0]
	a.Age = split[1]
	return nil
}

func main() {

	jsonbuf := `
	{
		"bookname":"booker",
		"author": "Tom:28"
	}`

	var book Book
	err := json.Unmarshal([]byte(jsonbuf), &book)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("book = %+v\n", book)
  // book = {BookName:booker Author:{Name:Tom Age:28}}
}

Related

Docker存储驱动direct-lvm的配置
·518 字·3 分钟
Docker Direct-Lvm
python脚本中调用shell的几种方法
·1177 字·6 分钟
Python
批量自动构建docker镜像的shell脚本
·580 字·3 分钟
Docker Shell