UnmarshalJSON Implementation for Derived Scalars in Go
Problem:
A custom type that converts subtyped integer constants to strings and vice versa requires automatic unmarshalling of JSON strings. This is challenging because UnmarshalJSON does not provide a way to modify the scalar value without using a struct.
Solution:
To implement UnmarshalJSON for a derived scalar type, consider the following steps:
Use a Pointer Receiver:
Use a pointer receiver for the UnmarshalJSON method to modify the value of the receiver.
Unmarshal to a String:
Unmarshal the JSON text into a plain string, removing all JSON quoting.
Lookup and Set Value:
Use the Lookup function to retrieve the corresponding PersonID based on the string value. Assign the result to the receiver.
Example:
func (intValue *PersonID) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } *intValue = Lookup(s) return nil }
Code Example:
package main import ( "encoding/json" "fmt" ) type PersonID int const ( Bob PersonID = iota Jane Ralph Nobody = -1 ) var nameMap = map[string]PersonID{ "Bob": Bob, "Jane": Jane, "Ralph": Ralph, "Nobody": Nobody, } var idMap = map[PersonID]string{ Bob: "Bob", Jane: "Jane", Ralph: "Ralph", Nobody: "Nobody", } func (intValue PersonID) Name() string { return idMap[intValue] } func Lookup(name string) PersonID { return nameMap[name] } func (intValue *PersonID) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } *intValue = Lookup(s) return nil } type MyType struct { Person PersonID `json: "person"` Count int `json: "count"` Greeting string `json: "greeting"` } func main() { var m MyType if err := json.Unmarshal([]byte(`{"person": "Ralph", "count": 4, "greeting": "Hello"}`), &m); err != nil { fmt.Println(err) } else { for i := 0; iOutput:
Hello Ralph Hello Ralph Hello Ralph Hello Ralph
The above is the detailed content of How to Implement UnmarshalJSON for Derived Scalar Types in Go?. For more information, please follow other related articles on the PHP Chinese website!

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

The article discusses using Go's "strings" package for string manipulation, detailing common functions and best practices to enhance efficiency and handle Unicode effectively.

The article details using Go's "crypto" package for cryptographic operations, discussing key generation, management, and best practices for secure implementation.Character count: 159

The article details the use of Go's "time" package for handling dates, times, and time zones, including getting current time, creating specific times, parsing strings, and measuring elapsed time.

Article discusses using Go's "reflect" package for variable inspection and modification, highlighting methods and performance considerations.


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.

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

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
