Godot 4.1中如何通过HTTPRequest获取正常JSON数据?
解决Godot HTTPRequest返回字节数组无法解析为JSON的问题
你的问题出在回调函数中对body参数的处理方式错误:body是一个字节数组(PoolByteArray),直接用str(body)会把数组转换成类似[123, 10, ...]的字符串,而不是将字节解码为UTF-8格式的JSON文本。
修正后的代码
func makeLoginRequest(): var url = "https://chocolatefactory-api.dreamstudio.my/login" var data = { "username": "test0001", "password": "test0001" } var http_request = HTTPRequest.new() add_child(http_request) http_request.connect("request_completed", Callable(self, "_on_request_completed")) http_request.request(url, ["Content-Type: application/json"], HTTPClient.METHOD_POST, JSON.new().stringify(data)) func _on_request_completed(result, response_code, headers, body): if response_code == 200: print("请求成功!!") # 关键修正:将字节数组解码为UTF-8字符串 var json_text = String(body) # 或 body.get_string_from_utf8() var json_parser = JSON.new() var parse_result = json_parser.parse(json_text) # 检查解析是否成功 if parse_result == OK: var json_data = json_parser.get_data() print("解析后的JSON数据:", json_data) # 可直接访问字段,比如 json_data["token"] else: print("JSON解析失败:", json_parser.get_error_message()) else: print("请求失败,错误码:", response_code)
核心修改点
- 用
String(body)或body.get_string_from_utf8()将字节数组解码为JSON字符串,而非str(body) - 增加JSON解析的错误检查,避免解析失败时出现未知问题
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

