Go语言设置JSON的默认值

给需要设置的JSON字段初试化你想设置的值就OK。
比如我想让[]string类型的字段的默认值是[],而不是nil,那我就make([]string, 0)赋值给该字段。
转成JSON输出后,就是[]

1. 示例代码

这是没有初始化的代码。默认值是nil。

package main

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
)

type JsonTest struct {
		Test1        string            `json:"test1"`
		Test2        []string					 `json:"test2"`
}

//定义自己的路由器
type MyMux1 struct {
}

//实现http.Handler这个接口的唯一方法
func (mux *MyMux1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	urlPath := r.URL.Path
	switch urlPath {
	case "/test":
		mux.testJson(w, r)
	default:
		http.Error(w, "没有此url路径", http.StatusBadRequest)
	}
}

func (mux *MyMux1) testJson(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "the method is not allowed", http.StatusMethodNotAllowed)
	}

	jsontest := &JsonTest{}
	//只初始化Test1字段
	jsontest.Test1 = "value1"
	
	jsondata,_ := json.Marshal(jsontest)
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, "%s", jsondata)
}

func main() {
	//实例化路由器Handler
	mymux := &MyMux1{}
	//基于TCP服务监听8088端口
	ln, err := net.Listen("tcp", ":8089")
	if err != nil {
		fmt.Printf("设置监听端口出错...")
	}
	//调用http.Serve(l net.Listener, handler Handler)方法,启动监听
	err1 := http.Serve(ln, mymux)
	if err1 != nil {
		fmt.Printf("启动监听出错")
	}
}

示例结果如下图1所示,字段Test2的默认值是nil

以下是对[]string字段初始化的代码。默认输出值是[]

func (mux *MyMux1) testJson(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "the method is not allowed", http.StatusMethodNotAllowed)
	}

	jsontest := &JsonTest{}

	jsontest.Test1 = "value1"
	jsontest.Test2 = make([]string, 0)

	jsondata,_ := json.Marshal(jsontest)
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, "%s", jsondata)
}

示例结果如下图2所示。

2. 示例结果

图一
图2

3. 总结

其他字段想要设置默认输出值,只需要对其进行相应的初始化即可。

发布了67 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/sinat_32336967/article/details/97175802