英文:
Why doesn't this JSON decode into my struct?
问题
我在调用JSON.stringify后发送了这样的数组:
{
"世": 1,
"界": 1,
"最": 1,
"強": 1
}
但是在使用json.NewDecoder.Decode时遇到了问题,我的结构体是否有问题?
type text struct {
Text map[string]int
}
我还遇到了将数据发送回前端的问题,如何将数据转换回[]byte,或者是否有其他可用的方法将JSON发送回前端?
func PostHandler(w http.ResponseWriter, r *http.Request){
log.Println("post start")
if r.Method != "POST" {
log.Println("in post but early return")
http.NotFound(w, r)
return
}
decoder := json.NewDecoder(r.Body)
var t text
err := decoder.Decode(&t)
if err != nil {
log.Println("I tried")
log.Println(r.Body)
}
log.Println(t.Text)
//w.Write([]byte(t.Text)) //throws conversion error
}
(我试图在前后端之间发送数据以掌握基础知识,然后再进行扩展)
另外,日志中打印的内容是:
post start
map[]
英文:
I am sending this kind of array after calling JSON.stringify on it
{
"世": 1,
"界": 1,
"最": 1,
"強": 1
}
but am having trouble using json.NewDecoder.Decode on it, is my struct wrong?
type text struct {
Text map[string]int
}
I am also having trouble sending that data back to the front end, how do I convert my data back to []byte or is there another method available to send json back to front end?
func PostHandler(w http.ResponseWriter, r *http.Request){
log.Println("post start")
if r.Method != "POST" {
log.Println("in post but early return")
http.NotFound(w, r)
return
}
decoder := json.NewDecoder(r.Body)
var t text
err := decoder.Decode(&t)
if err != nil {
log.Println("I tried")
log.Println(r.Body)
}
log.Println(t.Text)
//w.Write([]byte(t.Text)) //throws conversion error
}
(I am trying to send data back and forth between front and back end to get the basics down before moving on and expanding)
Also what's printed from the log is
post start
map[]
答案1
得分: 3
将JSON值直接解码为map[string]int
。该映射对应于JSON值中的一个对象。
decoder := json.NewDecoder(r.Body)
var t map[string]int
err := decoder.Decode(&t)
if err != nil {
log.Println("我尝试了")
log.Println(r.Body)
}
log.Println(t)
英文:
Decode the JSON value directly to a map[string]int
. The map corresponds to the one object in the JSON value.
decoder := json.NewDecoder(r.Body)
var t map[string]int
err := decoder.Decode(&t)
if err != nil {
log.Println("I tried")
log.Println(r.Body)
}
log.Println(t)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论