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

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

添加一個字段到 JSON ( 結構 + 接口 ) golang

添加一個字段到 JSON ( 結構 + 接口 ) golang

Go
米脂 2022-09-19 14:45:45
這是響應接口:type Response interface{}它滿足于這樣的結構:type CheckResponse struct {    Status    string `json:"status"`}我正在獲得一個輸出,它將在其他地方消費。out []Response我想在發送之前向此 JSON 添加一個字符串。我嘗試過使用匿名結構(但徒勞無功):Versionfor _, d := range out {        outd := struct {            Resp       Response `json:",inline"`            Version    string   `json:",inline"`        }{            Resp:       d,            Version: "1.1",        }        data, _ := json.Marshal(outd)        log.Infof("response : %s", data)    }我得到的輸出是:response : {"Resp":{"status":"UP"},"Version":"1.1"}我想要的是{"status":"UP","Version":"1.1"}即一個平面 JSON。
查看完整描述

3 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

斷言您的檢查響應類型,然后像這樣定義動態結構d


outd := struct {

            Resp       string `json:"status,inline"`

            Version    string   `json:",inline"`

        }

這是完整的代碼。


package main


import (

    "encoding/json"

    "fmt"

)


type Response interface {}


type CheckResponse struct {

    Status    string `json:"status"`

}


func main() {

    out := []Response{

        CheckResponse{Status: "UP"},

    }

    for _, d := range out {

        res, ok := d.(CheckResponse)

        if !ok {

            continue

        }

        outd := struct {

            Resp       string `json:"status,inline"`

            Version    string   `json:",inline"`

        }{

            Resp:       res.Status,

            Version: "1.1",

        }

        data, _ := json.Marshal(outd)

        fmt.Printf("response : %s", data)

    }

}

你可以在這里運行


查看完整回答
反對 回復 2022-09-19
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

inline標記不受 支持,嵌入接口也不會產生您想要的結果。您必須為值聲明一個類型,并讓該類型實現接口,然后您可以自定義其字段的封送方式,例如,您可以分別封送兩個字段 Resp 和 Version,然后將結果“合并”到單個 json 對象中。encoding/jsonoutjson.Marshaler


type VersionedResponse struct {

    Resp    Response

    Version string

}


func (r VersionedResponse) MarshalJSON() ([]byte, error) {

    out1, err := json.Marshal(r.Resp)

    if err != nil {

        return nil, err

    }

    out2, err := json.Marshal(struct{ Version string }{r.Version})

    if err != nil {

        return nil, err

    }


    // NOTE: if Resp can hold something that after marshaling

    // produces something other than a json object, you'll have

    // to be more careful about how you gonna merge the two outputs.

    //

    // For example if Resp is nil then out1 will be []byte(`null`)

    // If Resp is a slice then out1 will be []byte(`[ ... ]`)


    out1[len(out1)-1] = ',' // replace '}' with ','

    out2 = out2[1:]         // remove leading '{'


    return append(out1, out2...), nil

}

https://play.golang.org/p/66jIYXGUtWJ


查看完整回答
反對 回復 2022-09-19
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

一種確定可行的方法是簡單地使用 ,通過反射迭代中的字段,或者使用像 ,使用響應字段更新映射,將版本字段附加到映射,然后封送。下面是一個示例map[string]interface{}Responsestructs


package main


import (

    "encoding/json"

    "fmt"

    "github.com/fatih/structs"

)


type Response interface{}


type CheckResponse struct {

    Status string `json:"status"`

}


func main() {

    resp := CheckResponse{Status: "success"}

    m := structs.Map(resp)

    m["Version"] = "0.1"

    out, _ := json.Marshal(m)   

    

    fmt.Println(string(out))

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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