Home> System Tutorial> LINUX> body text

Serialization and deserialization of json data

王林
Release: 2024-01-09 11:30:17
forward
4104 people have browsed it
Introduction The full name of json is Javascript object notation, and the full Chinese name is: js object notation. Among the serialization and deserialization protocols, there are: json, xml, yaml, protocol buffer, etc. Among them, json is the main transmission form of front-end and back-end API contract data. json supports four data types: numeric values, Boolean values, arrays and objects. With these four data types, complex data models can be built.

In the Go language, we can use the json standard library to implement data serialization and deserialization. This library provides convenient methods to serialize and deserialize maps, structures, arrays, slices, and built-in primitive data types. By using the json standard library we can easily convert the data into json format and parse it back to the original data type when needed. This provides us with great convenience in processing data.

Here, I will give three examples to illustrate the use of json. For beginners, you may often use only one structure object to receive and send data. Let's take a look at specific examples below. 1. Use a structure object to receive data: ``` type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { data := `{"name": "Alice", "age": 25}` var p Person err := json.Unmarshal([]byte(data), &p) if err != nil { fmt.Println("Failed to parse json:", err) return

Serialization and deserialization of json data

Structure

type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}


func main() {
var (
newPer Person
bts []byte
)
per:=Person{
Name: "Lily",
Age: 29,
}
// Serialization
if bts, err = json.Marshal(per); err !=nil{
log.Fatal(err.Error())
return
}


if err = json.Unmarshal(bts, &newPer); err !=nil{
log.Fatal(err.Error())
return
}
fmt.Println(newPer)
}

map

func main() {
var (
smap = map[string]int{
"Age": 28,
"Sex": 1,
"Floor": 12,
}
newSmap = make(map[string]int)
bts []byte
)
if bts, err = json.Marshal(smap); err !=nil {
log.Fatal(err.Error())
return
}
if err = json.Umarshal(bts, &newSmap); err !=nil {
log.Fatal(err.Error())
return
}
fmt.Println(newSmap)
}

Array or slice dynamic array

func main() {
var (
ages []int = []int{23, 20, 28, 25, 30}
bts []byte
err error
newAges = make([]int, len(ages))
)
if bts, err = json.Marshal(ages); err != nil {
fmt.Println(err.Error())
return
}
if err = json.Unmarshal(bts, &newAges); err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("new ages: ", newAges)
return
}

Beginners are relatively clear about json serialization and deserialization of structures, but they may rarely or never use the latter two.

  • For array type data, but some business scenarios front-end will use it.
  • For the map type, when the third-party REST interface is called on the Go language server, the server only wants the specified return code to determine whether the call is successful. The programmer didn't want to write the overall struct structure definition, or maybe he was lazy, so he used a map[string]interface{} to receive the return data. At this time, after deserializing through Unmarshal in the json standard library, the return code is obtained through map["err_code"].(int), and then other subsequent processing logic is done.

Here we also need to explain the features that I sometimes use when using a structure. The tag value feature omitempty supported by the json of the structure, for example:
type Person struct {
Name string `json:"name,omitempty"`
Age int `json:"age"`
}
It means that when the tag value of function omitempty is set, if the data element value of the corresponding structure is zero, it will not be output. That is to say, if an element in the structure data returned by the server is empty and this element is not returned to the front end, you can use the json tag value attribute of omitempty.

Here we provide you with a json parsing library written by Taowen, a senior engineer of Didi Company, which is the fastest in the world. github address: jsoniter.

The article is reprinted from Open Source China Community [http://www.oschina.net]

The above is the detailed content of Serialization and deserialization of json data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:linuxprobe.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!