-1

I have this validation for when I receive a JSON String to validate if it is a JSONArray but I think there must be something better out there, im reading an inputStream from a rest service connection, then im gonna check if that String is either a JSONArray or just a JSONObject, after it goes into the validation "charAt(0) == '[' it won't go into the validation cadenaJSON instanceof JSONArray, do you guys know a better way to do this?

 while ((cadenaLectura = br.readLine()) != null) {
                    cadenaJSON = cadenaJSON.concat(cadenaLectura);
            }
            conn.disconnect();
            // If cadenaJSON starts with [ its because its a JSONArray
            if (cadenaJSON.charAt(0) == '[') {
                // This one isn't working
                if ((Object) cadenaJSON instanceof JSONArray) {
                    System.out.println("Soy un JSONArray");
                }
                JSONArray jsonArray = new JSONArray(cadenaJSON);
                return jsonArray.toString();
            } else {
                JSONObject json = new JSONObject(cadenaJSON);
                return json.toString();
            }
BugsForBreakfast
  • 712
  • 10
  • 30
  • 3
    Use a `JSON` library that can parse strings. Try to parse, catch `ParseException` (or whatever). If there's no exception, the string is valid `JSON`. – The Head Rush Jun 14 '19 at 14:22
  • Hmm like which libraries man? Im using JSONObject and JSONArray from primefaces and gson from google for casting json to java objects – BugsForBreakfast Jun 14 '19 at 14:41

1 Answers1

2

As noted in a comment, you really should use a JSON library to parse your response and check whether you got a valid array. Here's one example:

import org.json.*;

....

public boolean isJSONArray(String input) {
    try {
        new JSONArray(input);
        return true;
    } catch (JSONException ex) {
        return false;
    }
}

Do note that charAt(0) == '[' approach will give incorrect results when you have a malformed JSON (i.e. not a JSON string) or when you have whitespace before the opening [ char. Consider this string: ["string 1", nothing

Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • My example is using org.json - https://mvnrepository.com/artifact/org.json/json - but there are other options. You can use javax.json library for instance. – Aleks G Jun 14 '19 at 14:45
  • Yeah I just used primefaces json library, it worked too, my question is why is this a better approach than the charAt(0) == '[' method? – BugsForBreakfast Jun 14 '19 at 14:54
  • @DanielV Because `charAt(0) == '['` approach will give incorrect results when you have a malformed JSON (i.e. not a JSON string) or when you have whitespace before the opening `[` char. Consider this string: `["string 1", nothing` – Aleks G Jun 14 '19 at 14:55