doukanxi4246 2015-02-01 03:58
浏览 32
已采纳

为什么此JSON不解码为我的结构?

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条回答 默认 最新

  • dtd5644 2015-02-01 04:44
    关注

    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)
    

    similar playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog