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
type Person struct {<br>
Name string `json:"name"`<br>
Age int `json:"age"`<br>
}
<br>
func main() {<br>
var (<br>
newPer Person<br>
bts []byte<br>
)<br>
per:=Person{<br>
Name: "Lily",<br>
Age: 29,<br>
}<br>
// Serialization<br>
if bts, err = json.Marshal(per); err !=nil{<br>
log.Fatal(err.Error())<br>
return<br>
}
<br>
if err = json.Unmarshal(bts, &newPer); err !=nil{<br>
log.Fatal(err.Error())<br>
return<br>
}<br>
fmt.Println(newPer)<br>
}
func main() {<br>
var (<br>
smap = map[string]int{<br>
"Age": 28,<br>
"Sex": 1,<br>
"Floor": 12,<br>
}<br>
newSmap = make(map[string]int)<br>
bts []byte<br>
)<br>
if bts, err = json.Marshal(smap); err !=nil {<br>
log.Fatal(err.Error())<br>
return<br>
}<br>
if err = json.Umarshal(bts, &newSmap); err !=nil {<br>
log.Fatal(err.Error())<br>
return<br>
}<br>
fmt.Println(newSmap)<br>
}
func main() {<br>
var (<br>
ages []int = []int{23, 20, 28, 25, 30}<br>
bts []byte<br>
err error<br>
newAges = make([]int, len(ages))<br>
)<br>
if bts, err = json.Marshal(ages); err != nil {<br>
fmt.Println(err.Error())<br>
return<br>
}<br>
if err = json.Unmarshal(bts, &newAges); err != nil {<br>
fmt.Println(err.Error())<br>
return<br>
}<br>
fmt.Println("new ages: ", newAges)<br>
return<br>
}
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 {<br>
Name string `json:"name,omitempty"`<br>
Age int `json:"age"`<br>
}<br>
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.
- Detailed introduction of OpenFermion: click to view
- OpenFermion download address: click to download
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!

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy

The average annual salary of Linux administrators is $75,000 to $95,000 in the United States and €40,000 to €60,000 in Europe. To increase salary, you can: 1. Continuously learn new technologies, such as cloud computing and container technology; 2. Accumulate project experience and establish Portfolio; 3. Establish a professional network and expand your network.

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

Introduction Linux is a powerful operating system favored by developers, system administrators, and power users due to its flexibility and efficiency. However, frequently using long and complex commands can be tedious and er

Linux is suitable for servers, development environments, and embedded systems. 1. As a server operating system, Linux is stable and efficient, and is often used to deploy high-concurrency applications. 2. As a development environment, Linux provides efficient command line tools and package management systems to improve development efficiency. 3. In embedded systems, Linux is lightweight and customizable, suitable for environments with limited resources.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.