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)
}
}
你可以在這里運行

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

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))
}
- 3 回答
- 0 關注
- 152 瀏覽
添加回答
舉報