0

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?

atkayla
  • 8,143
  • 17
  • 72
  • 132
  • 1
    try to print the string of byte array which causes the exception. – Vishal Patel Jul 05 '19 at 18:09
  • *"I can't read a byte array"* You are converting the byte array to a String, which you then give to the JSON parser. You can read a String, can't you? Try printing it to see what it contains. See also [What's the simplest way to print a Java array?](https://stackoverflow.com/q/409784/5221149) – Andreas Jul 05 '19 at 18:24

2 Answers2

1

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!");
Qingfei Yuan
  • 1,196
  • 1
  • 8
  • 12
1

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);
Behdad
  • 184
  • 3
  • 12
  • Thanks, this was exactly it! There are are a few cases where it doesn't return JSON, but some garbled format `��q�s�A��Oքh��U�P�E>tT�jj�� ���9I<�f�)_��*=�[O��������: @ �쩭�Ka�`{��8�`m��$g�h��k�B`, which I did not expect. – atkayla Jul 05 '19 at 18:43