将字节数组转换为JSON错误无效的JSON

时间:2019-07-05 17:54:29

标签: java

我正在尝试将byte[]转换为类似{"foo": [{...}, {...}, ...], "bar": []}

的JSON
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]异常。

>如果不先读取字节数组又无法确定输入包含的内容,那么不先将其转换为会引发错误的JSON,该如何找出导致该问题的字符?

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);