dqjcb132285 2017-10-12 16:24
浏览 68
已采纳

无法在golang中解封json python后的请求

Here is my python code (client side) :

import requests
import json
import datetime
headers = {'Content-type': 'application/json',"Authorization":"Bearer MYREALLYLONGTOKENIGOT" }
url = 'http://127.0.0.1:9210/59c94c860a52840958543027/comment/59dea421c26d684270e9321e'
data = { 'sender' : '59c94c860a52840958543027', 'receiver':'59dea421c26d684270e9321e',
        'score' :5,
        'text':'tres jolie 2'}
data_json = json.dumps(data)
r = requests.post(url=url,headers=headers,json=data_json)
r.json()

And here is my golang server side code :

type CommentSent struct {
    Sender    string `json:"sender,omitempty"`
    Receiver  string `json:"receiver,omitempty"`
    Score     int `json:"score,omitempty"`
    Text      string `json:"text,omitempty"`
}


func PostComment(w http.ResponseWriter, r *http.Request) {
    var token string
    token = getToken(r)
    fmt.Println(token)
    vars := mux.Vars(r)
    idUser := vars["idUser"]
    idUserReceiver := vars["idUserReceiver"]
    fmt.Println(idUser)
    fmt.Println(idUserReceiver)
    var commentSend = CommentSend{}
    // body, err := ioutil.ReadAll(r.Body)
    // log.Println(string(body))
    decoder := json.NewDecoder(r.Body)
    err := decoder.Decode(&commentSend)
    if (err != nil){
        Info.Println("error")
        Info.Println(err)

    }

here is what give me the commented lines :

2017/10/12 18:21:29 "{\"sender\": \"59c94c860a52840958543027\", \"score\": 5, \"receiver\": \"59dea421c26d684270e9321e\", \"text\": \"tres jolie 2\"}"

and here is the error that i get :

INFO: 2017/10/12 18:22:32 comment.go:235: json: cannot unmarshal string into Go value of type main.CommentSent

And i don't understand why i have this error the json and python part seems correct and also the golang server side seems also correct.

  • 写回答

2条回答 默认 最新

  • douzhuo6931 2017-10-12 16:33
    关注

    Your entire request body is a quoted JSON string, rather than raw JSON.

    "{\"sender\":....
    

    Either send raw JSON, i.e.:

    {"sender":...
    

    Or un-escape it in your Go program. Sending raw JSON is probably the better solution. How to do that, I don't know, as I'm not a Python guru.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题