我正在尝试将byte[]
转换为类似{"foo": [{...}, {...}, ...], "bar": []}
try {
byte[] response = getExternalServiceResponse();
JSONObject json = new JSONObject(new String(response));
log.info(json.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
这适用于大多数响应情况,但是有些响应会引发org.json.JSONException: A JSONObject text must begin with '{' at 3 [character 2 line 2]
异常。
答案 0 :(得分:1)
我同意使用Exception判断不是一个好主意。也许您可以轻易地告诉它自己无效。
byte[] response = getExternalServiceResponse();
String resStr = new String(response).trim();
if(!resStr.startWith("{")) throw Exception("invalid json input!");
答案 1 :(得分:1)
这也许是因为有时您的服务会返回错误或类似于json的错误,例如“此处发生了某些错误!;-)”
最好先记录您的响应,然后再将其转换为json。甚至最好验证其json模式以进行生产部署。
String strResponse = new String(response).trim();
log.info( strResponse);