golang 模拟json编码

本文只是模拟json序列化的过程

源码如下:

package main

import "fmt"

// JSONData is json obj
type JSONData struct {
	code    int
	message string
	data    []string
}

// Phone struct is defined as pixel
type Phone struct {
	width  int
	height int
}

func tojson(code int, message string, screen Phone) (JSONData, error) {
	var obj JSONData 
	obj.code = code
	obj.message = message
	obj.data = append(obj.data, fmt.Sprintf("{width:%d,height:%d}", screen.width, screen.height))
	return obj, nil
}

func main() {
	obj, err := tojson(0, "hello woirld", Phone{100, 200})
	if err != nil {
		fmt.Printf("error")
		return
	}
	fmt.Printf(obj.data[0])
}

在vscode 执行结果如下:

API server listening at: 127.0.0.1:31242
{width:100,height:200}
Process exiting with code: 0
发布了86 篇原创文章 · 获赞 71 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/jacky128256/article/details/104681055