使用 Go,我想接受带有 json 数据的请求,并将其转换为传出 json 请求的不同结构。
这是我的意思的一个例子:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Greetings struct {
Greetings []Greeting `json:"data"`
}
type Greeting struct {
From string `json:"from"`
To string `json:"to"`
Greeting string `json:"greeting"`
}
type RelationShip struct {
Messages []Message `json:"data"`
}
type Message struct {
From string `json:"from"`
To string `json:"to"`
Message string `json:"message"`
}
func main() {
http.HandleFunc("/", Greet)
http.ListenAndServe(":3000", nil)
}
func Greet(rw http.ResponseWriter, request *http.Request) {
decoder := json.NewDecoder(request.Body)
var greetings Greetings
err := decoder.Decode(&greetings)
if err != nil {
panic(err)
}
for _, g := range greetings.Greetings {
fmt.Printf("%s, to %s from %s.\n", g.Greeting, g.To, g.From)
}
relationShip := &RelationShip{Messages: greetings.Greetings}
r, err := json.Marshal(&relationShip)
if err != nil {
panic(err)
}
fmt.Println(string(r))
}
这是一个 curl 请求示例
curl -d '{"data": [{"to":"drew","from":"jo","greeting":"Hey"}, \
{"to":"lori", "from":"yuri","greeting":"what up?"}]}' \
http://localhost:3000
我想也许我可以逃避这样的事情:
relationShip := &RelationShip{Messages: greetings.Greetings}
但是我不能将 []Greeting 类型用作 []Message 类型。我对 Go 和一般的静态类型语言真的很陌生。我是否遍历问候语列表并将它们作为新的消息项推送到消息中?
要点:我正在编写一个 API,它可以接收传入请求,并将其发送到正确的第三方 API,该 API 将始终关注相同的数据,但可能具有不同的 key .因此,对实际问题和/或更好方法的提示表示赞赏和欢迎:)
最佳答案
正如您所注意到的,您不能将 []Greeting 类型用作 []Message 类型。因为它们不是同一种类型。然而,有一种方法可以从一种类型转换为另一种类型,但它需要 identical类型。
例如,以下将起作用:
type Message struct {
From string `json:"from"`
To string `json:"to"`
Message string `json:"message"`
}
type Greeting struct {
From string `json:"from"`
To string `json:"to"`
Message string `json:"message"`
}
func main() {
mess := Message{"from", "to", "message"}
fmt.Println(reflect.TypeOf(mess))
// > Message
greet := Greeting(mess)
fmt.Println(reflect.TypeOf(greet))
// > Greeting
}
但要求字段相同,json标签也相同。
在您的情况下,遍历问候语并将其转换为消息将毫无问题。
关于json - 通过 JSON API 将嵌套结构映射到具有相同数据的不同嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37266025/