1、将结构体转换成json需要用到marshl函数(或者marshlIndent()函数)。
区别:marshl函数没有将json格式化输出,输出是一个json的字符串。----不利于直接查看json的结构。maeshldent函数
可以将json格式化输出,可阅读性提高了。
2、将json字符串转换成结构体需要用到marshl()函数。
实例如下:
```go
package main
import (
"log"
"encoding/json"
"fmt"
)
type Movie struct{
Title string
Year int `json:"released"`
Color bool `json:"color, omitempty"`
Actors []string
}
func main(){
var movies = []Movie{
{Title:"Casabanca", Year: 1942, Color:false,
Actors:[]string{"Humphrey Bogart", "Ingrid Bergman"}},
{Title:"Casabanca2", Year: 1962, Color:true,
Actors:[]string{"Humphrey Paul"}},
}
data, err := json.Marshal(movies)
if err != nil {
log.Fatalf("Json marshaling failed:%s", err)
}
fmt.Printf("%s\n", data)
var movies2 []struct{Title string}
// movies2 := make([]Movie, 10)
if err3 := json.Unmarshal(data, &movies2); err3 !=nil{
log.Fatalf("JSON unmarshling failed: %s", err)
}
fmt.Println("*****************", movies2)
data2, err2 := json.MarshalIndent(movies, ""," ")
if err2 != nil {
log.Fatalf("Json marshlindent failed:%s", err)
}
fmt.Printf("%s\n", data2)
}
//2
package main
import (
"log"
"encoding/json"
"fmt"
)
type Movie struct{
Title string
Year int `json:"released"`
Color bool `json:"color, omitempty"`
Actors []string
}
func main(){
var movies = []Movie{
{Title:"Casabanca", Year: 1942, Color:false,
Actors:[]string{"Humphrey Bogart", "Ingrid Bergman"}},
{Title:"Casabanca2", Year: 1962, Color:true,
Actors:[]string{"Humphrey Paul"}},
}
data, err := json.Marshal(movies)
if err != nil {
log.Fatalf("Json marshaling failed:%s", err)
}
fmt.Printf("%s\n", data)
var movies2 []struct{Title string}
// movies2 := make([]Movie, 10)
if err3 := json.Unmarshal(data, &movies2); err3 !=nil{
log.Fatalf("JSON unmarshling failed: %s", err)
}
fmt.Println("*****************", movies2)
data2, err2 := json.MarshalIndent(movies, ""," ")
if err2 != nil {
log.Fatalf("Json marshlindent failed:%s", err)
}
fmt.Printf("%s\n", data2)
}
```
有疑问加站长微信联系(非本文作者))