【问题标题】:Unmarshalling JSON from the http POST request从 http POST 请求中解组 JSON
【发布时间】:2017-01-05 13:17:30
【问题描述】:

我有一个用 Go 编写的简单服务器:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "io/ioutil"
    "net/http"
)

type Game struct {
    RID     string `json: "RID"`
    Country string `json: "Country"`
}

func postWaitingGames(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Println(err)
    }
    var game Game

    err = json.Unmarshal(body, &game)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%v\n", game)

    defer r.Body.Close()
}

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/wait/", postWaitingGames).Methods("POST")

    http.ListenAndServe(":8081", router)
}

还有一个用 Python 编写的用于测试目的的简单客户端。代码如下:

import json
import requests

json_to_send = json.dumps({"RID": "8", "Country": "Australia"})

post_headers = {'Content-type': 'application/json'}
addr = "http://127.0.0.1:8081/wait/"
resp = requests.post(url=addr, json=json_to_send, headers=post_headers)
print(resp.status_code)

每次客户端访问服务器时,后者都会产生此错误:

json: cannot unmarshal string into Go value of type main.Game

我知道Handling JSON Post Request in Go

Python 版本 == 3.4 Go 版本 == 1.7

提前谢谢你。

【问题讨论】:

    标签: python json http go marshalling


    【解决方案1】:

    如果使用requests.post()json 参数,您必须将Python dict 传递给您,而不是json 序列化版本-requests 将负责调用json.dumps()。在这里,您最终会将您的 dict 序列化两次。

    另外 - 总是在使用 json 参数时 - 你不需要设置内容类型标题,requests 也会处理这个问题。

    【讨论】:

      【解决方案2】:

      所以,按照 thisthis 之类的教程,我遇到了 unmarshall 错误,我认为您有两个选择使用 requests(当内容类型为 JSON):

      payload = {
          "userId": "so_cool_user",
      }
      

      答:

      requests.post(url=srvc_url, json=payload)
      

      乙:

      requests.post(url=srvc_url, data=json.dumps(payload))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-04
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多