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?

2
  • 1
    try to print the string of byte array which causes the exception. Commented Jul 5, 2019 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? Commented Jul 5, 2019 at 18:24

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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!");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.