英文:
In golang, nested structures are not encoding into httpresponse
问题
在我的golang代码中,我使用了net/http和gorilla mux。
在下面的函数中,当我对嵌套结构变量进行编码时,http响应显示为空的"{}"。然而,如果我只对非嵌套结构的其中一个进行编码,它们就可以正常显示。
请问如何在http响应中发送嵌套结构?谢谢
func getNestedStruct(w http.ResponseWriter, r *http.Request) {
type User1 struct {
ID int `json:"Id1"`
Email string `json:"Email1"`
Password string `json:"Password1"`
}
type User2 struct {
ID int `json:"Id2"`
Email string `json:"Email2"`
}
type Users struct {
MyUser1 User1 `json:"User1"`
MyUser2 User2 `json:"User2"`
}
var myUser1 User1
var myUser2 User2
var myUsers Users
myUser1.ID = 1
myUser1.Email = "user1@email.com"
myUser1.Password = "user1"
myUser2.ID = 2
myUser2.Email = "user2@email.com"
myUsers.MyUser1 = myUser1
myUsers.MyUser2 = myUser2
// 这些打印没有问题
log.Printf("getNestedStruct: Struct User1: ", myUser1)
log.Printf("getNestedStruct: Struct User2: ", myUser2)
log.Printf("getNestedStruct: Nested Struct Users: ", myUsers)
// 这个不起作用 --> 在http响应中显示{}
json.NewEncoder(w).Encode(myUsers)
// 这个可以正常工作:
//json.NewEncoder(w).Encode(myUser1)
}
英文:
In my golang code, I use net/http and gorilla mux.
In the function below, when I encode the nested structure variable, the http response shows blank "{}". However, if I encode only one of the non-nested struct's they show up ok.
Can you please help how I can send the nested-structure in http-response? Thank you
func getNestedStruct(w http.ResponseWriter, r *http.Request) {
type User1 struct {
ID int `json:"Id1"`
Email string `json:"Email1"`
Password string `json:"Password1"`
}
type User2 struct {
ID int `json:"Id2"`
Email string `json:"Email2"`
}
type Users struct {
MyUser1 User1 `json:"User1"`
MyUser2 User2 `json:"User1"`
}
var myUser1 User1
var myUser2 User2
var myUsers Users
myUser1.ID = 1
myUser1.Email = "user1@email.com"
myUser1.Password = "user1"
myUser2.ID = 2
myUser2.Email = "user2@email.com"
myUsers.MyUser1 = myUser1
myUsers.MyUser2 = myUser2
// these print without issues
log.Printf("getNestedStruct: Struct User1: ", myUser1)
log.Printf("getNestedStruct: Struct User2: ", myUser2)
log.Printf("getNestedStruct: Nested Struct Users: ", myUsers)
// This does not work --> shows {} in http response
json.NewEncoder(w).Encode(myUsers)
// This works:
//json.NewEncoder(w).Encode(myUser1)
}
答案1
得分: 1
MyUser1
和MyUser2
都有相同的JSON键。给予不同的键应该可以工作。
type Users struct {
MyUser1 User1 `json:"User1"`
MyUser2 User2 `json:"User2"`
}
英文:
MyUser1
& MyUser2
both have the same JSON key. Giving different keys should work
type Users struct {
MyUser1 User1 `json:"User1"`
MyUser2 User2 `json:"User2"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论