使用Go语言怎么对JSON的默认值进行设置-创新互联
使用Go语言怎么对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. 示例结果


3. 总结
其他字段想要设置默认输出值,只需要对其进行相应的初始化即可。
补充:golang json Unmarshal的时候,在key为空的时候给予默认值
我就废话不多说了,大家还是直接看代码吧~
package main
import (
"fmt"
"encoding/json"
)
type Test struct {
A string
B int
C string
}
func (t *Test) UnmarshalJSON(data []byte) error {
type testAlias Test
test := &testAlias{
A: "default A",
B: -2,
}
_ = json.Unmarshal(data, test)
*t = Test(*test)
return nil
}
var example []byte = []byte(`[{"A": "1", "C": "3"}, {"A": "4", "B": 2}, {"C": "5"}]`)
func main() {
out := &[]Test{}
_ = json.Unmarshal(example, &out)
fmt.Print(out)
}结果
&[{1 -2 3} {4 2 } {default A -2 5}]
可以看到 在key没有的情况下可以指定对应的值,这样就可以了。
看完上述内容,你们掌握使用Go语言怎么对JSON的默认值进行设置的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
网页标题:使用Go语言怎么对JSON的默认值进行设置-创新互联
网站链接:http://www.jxjierui.cn/article/dpdoeo.html


咨询
建站咨询
