1.将结构体转换为JSON:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int Email string } func main() { person := Person{Name: "Alice", Age: 25, Email: "alice@example.com"} jsonData, err := json.Marshal(person) if err != nil { fmt.Println("转换失败:", err) return } fmt.Println(string(jsonData)) }
2.将切片转换为JSON
package main import ( "encoding/json" "fmt" ) func main() { numbers := []int{1, 2, 3, 4, 5} jsonData, err := json.Marshal(numbers) if err != nil { fmt.Println("转换失败:", err) return } fmt.Println(string(jsonData)) } 答案解析:
3.将Map转换为JSON
package main import ( "encoding/json" "fmt" ) func main() { student := map[string]interface{}{ "name": "Bob", "age": 20, "gender": "male", } jsonData, err := json.Marshal(student) if err != nil { fmt.Println("转换失败:", err) return } fmt.Println(string(jsonData)) }
4.将JSON字符串转换为结构体
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int Email string } func main() { jsonData := `{"Name":"Alice","Age":25,"Email":"alice@example.com"}` var person Person err := json.Unmarshal([]byte(jsonData), &person) if err != nil { fmt.Println("反序列化失败:", err) return } fmt.Printf("姓名:%s,年龄:%d,邮箱:%s\n", person.Name, person.Age, person.Email) }
5.将JSON数组转换为切片:
go package main import ( "encoding/json" "fmt" ) func main() { jsonData := `[1,2,3,4,5]` var numbers []int err := json.Unmarshal([]byte(jsonData), &numbers) if err != nil { fmt.Println("反序列化失败:", err) return } fmt.Println(numbers) }
标签:类型转换,err,fmt,json,jsonData,Println,JSON,go,main From: https://www.cnblogs.com/superzwb/p/17544447.html