在 Golang 中,Unmarshal 用于将 JSON 或 XML 字符串转换为结构体或其他数据类型,它是将数据反序列化为 Go 语言对象的方法。

以下是 Golang Unmarshal 的用法:

  1. 使用 json.Unmarshal() 函数将 JSON 字符串转换为结构体:

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

var jsonStr = `{'name':'John', 'age':30}`
var person Person
json.Unmarshal([]byte(jsonStr), &person)
fmt.Println(person.Name, person.Age)
  1. 使用 xml.Unmarshal() 函数将 XML 字符串转换为结构体:

type Person struct {
   Name string `xml:'name'`
   Age  int    `xml:'age'`
}

var xmlStr = `<Person><name>John</name><age>30</age></Person>`
var person Person
xml.Unmarshal([]byte(xmlStr), &person)
fmt.Println(person.Name, person.Age)
  1. 使用 Unmarshal() 函数将 JSON 或 XML 字符串转换为 map[string]interface{}

var jsonStr = `{'name':'John', 'age':30}`
var jsonMap map[string]interface{}
json.Unmarshal([]byte(jsonStr), &jsonMap)
fmt.Println(jsonMap['name'], jsonMap['age'])

var xmlStr = `<Person><name>John</name><age>30</age></Person>`
var xmlMap map[string]interface{}
xml.Unmarshal([]byte(xmlStr), &xmlMap)
fmt.Println(xmlMap['name'], xmlMap['age'])

需要注意的是,Unmarshal() 函数的第二个参数必须是指向结构体或 map 的指针。另外,在使用 Unmarshal() 函数时,需要确保 JSON 或 XML 字符串的格式与结构体或 map 的定义相匹配。

Golang Unmarshal: JSON 和 XML 数据解析指南

原文地址: https://www.cveoy.top/t/topic/lZtR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录