Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

json/xml

json

Json can be converted to maps, structs, and interfaces

// Convert struct, map to JSON string
json.Marshal(struct|map)

// Convert the JSON string to a Person structure
type Person struct{... } jsonStr := []byte(`{"age":"18","name":"123.com","marry":false}`)
var p Person
json.Unmarshal(jsonStr,&p)
Copy the code

Weakly-typed JS and PHP can convert json strings dynamically and freely at any time, which is really comfortable. No wonder PHP developers always say arrays are powerful.

xml

The method is the same as the JSON package, but the data source is different

xml.Marshal(struct|map)
xml.Unmarshal(xmlStr,&p)
Copy the code
msgpack

MSGPack is binary JSON for faster performance and less space

Need to install third-party packages: go get -u github.com/vmihailenco/msgpack

msgpack.Marshal(struct|map)
msgpack.Unmarshal(msgpackbinary,&p)

Copy the code

A lot of times, we might run into situations where the JSON data returned from the remote end is not of the type you want, or if you want to do something extra, like check during parsing, or cast, then we can either do this or we can cast during parsing

package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
)
 
// Mail _
type Mail struct {
    Value string
}
 
// UnmarshalJSON _
func (m *Mail) UnmarshalJSON(data []byte) error {
    // If () {//
    if bytes.Contains(data, []byte("@")) {
        return fmt.Errorf("mail format error")
    }
    m.Value = string(data)
    return nil
}
 
// UnmarshalJSON _
func (m *Mail) MarshalJSON(a) (data []byte, err error) {
    ifm ! =nil {
        data = []byte(m.Value)
    }
    return
}
 
// Phone _
type Phone struct {
    Value string
}
 
// UnmarshalJSON _
func (p *Phone) UnmarshalJSON(data []byte) error {
    // If () {//
    if len(data) ! =11 {
        return fmt.Errorf("phone format error")
    }
    p.Value = string(data)
    return nil
}
 
// UnmarshalJSON _
func (p *Phone) MarshalJSON(a) (data []byte, err error) {
    ifp ! =nil {
        data = []byte(p.Value)
    }
    return
}
 
// UserRequest _
type UserRequest struct {
    Name  string
    Mail  Mail
    Phone Phone
}
 
func main(a) {
    user := UserRequest{}
    user.Name = "zhangsan"
    user.Mail.Value = "[email protected]"
    user.Phone.Value = "12345678"
    fmt.Println(json.Marshal(user))
}
Copy the code