亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將接口與 Golang Maps、Structs 和 JSON 結合使用

將接口與 Golang Maps、Structs 和 JSON 結合使用

Go
慕沐林林 2021-09-27 16:09:19
我有一些 JSON 代碼,看起來像:{    "message_id": "12345",    "status_type": "ERROR",    "status": {        "x-value": "foo1234",        "y-value": "bar4321"    }}或者看起來像這樣。如您所見,“status”元素根據 status_type 從標準字符串對象更改為字符串數組對象。{    "message_id": "12345",    "status_type": "VALID",    "status": {        "site-value": [            "site1",            "site2"        ]    }}我想我需要讓我的“狀態”結構采用像“map[string]interface{}”這樣的地圖,但我不確定如何做到這一點。您也可以在操場上看到這里的代碼。http://play.golang.org/p/wKowJu_lngpackage mainimport (    "encoding/json"    "fmt")type StatusType struct {    Id     string            `json:"message_id,omitempty"`    Status map[string]string `json:"status,omitempty"`}func main() {    var s StatusType    s.Id = "12345"    m := make(map[string]string)    s.Status = m    s.Status["x-value"] = "foo1234"    s.Status["y-value"] = "bar4321"    var data []byte    data, _ = json.MarshalIndent(s, "", "    ")    fmt.Println(string(data))}
查看完整描述

3 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

我想通了,我想..


package main


import (

    "encoding/json"

    "fmt"

)


type StatusType struct {

    Id     string            `json:"message_id,omitempty"`

    Status map[string]interface{} `json:"status,omitempty"`

}


func main() {

    var s StatusType

    s.Id = "12345"

    m := make(map[string]interface{})

    s.Status = m


    // Now this works

    // s.Status["x-value"] = "foo1234"

    // s.Status["y-value"] = "bar4321"


    // And this works

    sites := []string{"a", "b", "c", "d"}

    s.Status["site-value"] = sites


    var data []byte

    data, _ = json.MarshalIndent(s, "", "    ")


    fmt.Println(string(data))

}


查看完整回答
反對 回復 2021-09-27
  • 3 回答
  • 0 關注
  • 244 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號