我正在尝试使用 Python 请求将 JSON 发送到安装了 Jackson 的 Spring Boot 3.2 服务器。
Python JSON 从 Spring Boot 服务器生成 400 错误,Spring Boot 的错误日志状态如下:
JSON parse error: Cannot construct instance of `com.monkey.signalsdb.model.Timer`
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from
String value ('{ "start_date_time": "20240227-215731", "channel": 59, "snr": [ 15.5, 21.1, 26.8 ],
"dbfs": -23.56, "lat": -36.7453, "lon": 174.6837,
....
"end_date_time": "20240227-215731" }')]
如果将 Python 生成的 JSON 粘贴到 Postman 中,它将以正确的响应 201 发布到端点。
我正在我的 python 数据类中生成 JSON:
def toJSON(self):
return json.dumps({"start_date_time" : self.start_date_time.strftime("%Y%m%d-%H%M%S"), \
"channel" : self.channel, \
"snr" : self.snr, \
"dbfs" : self.dbfs, \
"lat" : self.lat, \
"lon" : self.lon, \
...
"end_date_time" : self.finish_date_time.strftime("%Y%m%d-%H%M%S")}, \
indent = 4)
我一直在尝试使用 Juypter 笔记本发送 JSON,以使用伪代码进行 fest 测试:
testjson = '{ "start_date_time": "20240227-215731", "channel": 59, "snr": [ 15.5, 21.1, 26.8 ],
"dbfs": -23.56, "lat": -36.7453, "lon": 174.6837, "carrier_freq": 160.12,
...
"end_date_time": "20240227-215731" }'
headers = {'Content-Type': 'application/json', 'Accept': '*/*'}
req = requests.post('http://localhost:8080/', json = testjson, headers=headers)
但结果是相同的 JSON 解析错误:无法构造实例。
当剪切并粘贴到 Postman 中时,是什么导致 JSON 工作,但不是用
requests
从 Python 本地发送?
我怀疑在 Python 中生成的 JSON,因为它在 Postman 中发送得很好。
问题出在
json: testjson
部分。这使得 requests
将字符串转换为 JSON。结果是一个 JSON 字符串。
来自
requests
的源代码:
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
要么不要自己转换为 JSON,要么使用
data
代替 json
。