golang中对象的json数据格式的处理(编码与解码)

代码:

package main

import (
	"encoding/json" //1.导包
	"fmt"
)

type Insure struct {
    
    
	Id    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
	PID   string  `json:"pid"`
}

func (i *Insure) GetName() interface{
    
    } {
    
    
	return i.Name
}

func (i *Insure) GetPrice() interface{
    
    } {
    
    
	return i.Price
}

func (i *Insure) GetPId() interface{
    
    } {
    
    
	return i.PID
}

func main() {
    
    
	insure := Insure{
    
    "2f45s54c45", "番茄农业", 200, "200456987566454"}
	//
	fmt.Printf("object data:%v\n", insure)
	//2.编码
	insureStr, err := json.Marshal(insure)
	if err != nil {
    
    
		fmt.Printf("%s", "marshal eroor")
	} else {
    
    
		fmt.Printf("json data:%s\n", insureStr)
	}
	//3.解码
	insure1 := Insure{
    
    }
	err = json.Unmarshal(insureStr, &insure1)
	if err != nil {
    
    
		fmt.Printf("%s", "unmarshal eroor")
	} else {
    
    
		fmt.Printf("object data:%v\n", insure1)
	}
}

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_51799151/article/details/126681602