atkayla
atkayla

Reputation: 8849

Convert byte array to JSON error invalid JSON

I am trying to convert a byte[] to JSON that looks like: {"foo": [{...}, {...}, ...], "bar": []}

try {
  byte[] response = getExternalServiceResponse();
  JSONObject json = new JSONObject(new String(response));
  log.info(json.toString(4));
} catch (Exception e) {
  e.printStackTrace();
}

This works for most cases of response but there are some that throw the exception with org.json.JSONException: A JSONObject text must begin with '{' at 3 [character 2 line 2]. How can I find out what characters are causing the issue as I can't read a byte array and I am not sure what the input contains without first converting it to JSON which throws the error?

Upvotes: 0

Views: 1348

Answers (2)

Behdad
Behdad

Reputation: 181

Maybe this is because sometimes your service returns an error or something similar which is not json, like "Some Error has occurred here! ;-)"

It is better to log your response before converting it to json.It is even better to validate its json schema for production deployment.

String strResponse = new String(response).trim();
log.info( strResponse);

Upvotes: 1

Qingfei Yuan
Qingfei Yuan

Reputation: 1212

I agree that use Exception to judge is bad idea. Maybe you can tell it invalidate by yourself easily.

byte[] response = getExternalServiceResponse();
String resStr = new String(response).trim();
if(!resStr.startWith("{")) throw Exception("invalid json input!");

Upvotes: 1

Related Questions