search
HomeBackend DevelopmentGolangGo language document interpretation: Detailed explanation of encoding/json.Unmarshaler interface

Go language document interpretation: Detailed explanation of encoding/json.Unmarshaler interface

Go language document interpretation: Detailed explanation of the encoding/json.Unmarshaler interface, specific code examples are required

Introduction:
In the Go language, the encoding/json package provides A series of functions and interfaces are provided to handle the encoding and decoding operations of JSON data. Among them, the json.Unmarshaler interface plays an important role in decoding JSON data. This article will explain the json.Unmarshaler interface in detail and provide specific code examples.

  1. Json.Unmarshaler interface introduction:
    json.Unmarshaler interface defines a custom type that can control how JSON data is decoded. The interface is defined as follows:

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

    Unmarshaler has only one method UnmarshalJSON([]byte) error, which is used to decode the incoming JSON byte slice and convert it to the target type.

  2. Use json.Unmarshaler interface:
    In order to use the Unmarshaler interface in a custom type, you need to implement the UnmarshalJSON([]byte) error method. The following is a sample code:
package main

import (
    "encoding/json"
    "fmt"
)

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

func (p *Person) UnmarshalJSON(data []byte) error {
    var v struct {
        Name  string `json:"Name"`
        Age   int    `json:"Age"`
        Email string `json:"Email"`
    }

    err := json.Unmarshal(data, &v)
    if err != nil {
        return err
    }

    p.Name = v.Name
    p.Age = v.Age
    p.Email = v.Email

    return nil
}

func main() {
    data := []byte(`{"Name":"John Doe","Age":30,"Email":"johndoe@example.com"}`)

    var p Person
    err := json.Unmarshal(data, &p)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
    fmt.Println("Email:", p.Email)
}

In the above code, we define a Person structure, in which the Name, Age and Email fields represent name, age and email respectively. The UnmarshalJSON([]byte) error method is implemented in the Person structure, through which the incoming JSON byte slice is decoded into a Person type object.

In the main function, we define a json data and then decode it into an object p of type Person. Finally, print out each field of Person.

  1. Summary:
    By implementing the json.Unmarshaler interface, we can customize the JSON decoding method of the type. Using the json.Unmarshaler interface can process JSON data more flexibly and adapt to various complex decoding requirements.

I hope this article will help you understand the role and usage of the json.Unmarshaler interface.

The above is the detailed content of Go language document interpretation: Detailed explanation of encoding/json.Unmarshaler interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Using init for Package Initialization in GoUsing init for Package Initialization in GoApr 24, 2025 pm 06:25 PM

In Go, the init function is used for package initialization. 1) The init function is automatically called when package initialization, and is suitable for initializing global variables, setting connections and loading configuration files. 2) There can be multiple init functions that can be executed in file order. 3) When using it, the execution order, test difficulty and performance impact should be considered. 4) It is recommended to reduce side effects, use dependency injection and delay initialization to optimize the use of init functions.

Go's Select Statement: Multiplexing Concurrent OperationsGo's Select Statement: Multiplexing Concurrent OperationsApr 24, 2025 pm 05:21 PM

Go'sselectstatementstreamlinesconcurrentprogrammingbymultiplexingoperations.1)Itallowswaitingonmultiplechanneloperations,executingthefirstreadyone.2)Thedefaultcasepreventsdeadlocksbyallowingtheprogramtoproceedifnooperationisready.3)Itcanbeusedforsend

Advanced Concurrency Techniques in Go: Context and WaitGroupsAdvanced Concurrency Techniques in Go: Context and WaitGroupsApr 24, 2025 pm 05:09 PM

ContextandWaitGroupsarecrucialinGoformanaginggoroutineseffectively.1)ContextallowssignalingcancellationanddeadlinesacrossAPIboundaries,ensuringgoroutinescanbestoppedgracefully.2)WaitGroupssynchronizegoroutines,ensuringallcompletebeforeproceeding,prev

The Benefits of Using Go for Microservices ArchitectureThe Benefits of Using Go for Microservices ArchitectureApr 24, 2025 pm 04:29 PM

Goisbeneficialformicroservicesduetoitssimplicity,efficiency,androbustconcurrencysupport.1)Go'sdesignemphasizessimplicityandefficiency,idealformicroservices.2)Itsconcurrencymodelusinggoroutinesandchannelsallowseasyhandlingofhighconcurrency.3)Fastcompi

Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

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