5.1 结构体输出为json格式
package main
import (
"encoding/json"
"fmt"
)
type Book struct {
Id int
Author string
Price int
}
func main(){
book := Book {
Id : 1,
Author : "haha",
Price : 232,
}
bookBytes, _ := json.Marshal(book)
fmt.Println("book = ", string(bookBytes))
}
结果:
book = {"Id":1,"Author":"haha","Price":232}
5.2 json格式字符串转结构体
package main
import (
"encoding/json"
"fmt"
)
type Book struct {
Id int
Author string
}
func main(){
var s = "{\"Id\":123, \"Author\": \"haha\"}"
var book Book
err := json.Unmarshal([]byte(s), &book)
if err == nil {
fmt.Println("book = ", book)
}
}
结果:
book = {123 haha}
5.3 使用new初始化对象
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
person := new(Person)
person.Name = "zhangsan"
person.Age = 123
fmt.Println("person = ", person)
}
结果:
person = &{zhangsan 123}