1024programmer Java Go language uses third-party package json structure operation example

Go language uses third-party package json structure operation example

The example in this article describes the use of third-party packages in go language to operate jsonized structures. Share it with everyone for your reference, the details are as follows:

Prerequisite: Install the git corresponding to the operating system

 go get -u github.com/pquerna/ffjson

 

-u parameter: If the package already exists locally, the update will be forced.

1. Since the structure is converted into a json string, let’s define a structure first
The code is as follows: // Define a structure
type NewsModel struct {
ID int
Title string
}

2. Let’s see what method the ffjson package uses to convert the structure into a json string
The code is as follows: func main() {
news := NewsModel{110,”hello”}
res,err := ffjson.Marshal(news)
if err != nil {
fmt.Println(“Format Error”)
fmt.Println(err.Error())
return
}
//The result is a byte array, so it needs to be converted to string
fmt.Println(string(res))
}

Print:

{“Id”:110,”Title”:”hello”}

got a json string

3. Expansion

Encapsulate a method ToJson() for the structure to do this specifically
The code is as follows: package main
import (
“fmt”
“github.com/pquerna/ffjson/ffjson”
)
//Define a structure
type NewsModel struct {
ID int
Title string
}
//Define a method
func (news NewsModel) ToJson() string {
res,err := ffjson.Marshal(news)
if err != nil {
return err.Error()
}
//The result is a byte array, so it needs to be converted to string
return string(res)
}
func main() {
news := NewsModel{110,”hello”}
fmt.Println(news.ToJson()) // Print: {“Id”:110,”Title”:”hello”}
}

I hope this article will be helpful to everyone in Go language programming.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/784272

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索