1

I've been trying to turn a string that I receive as a response from a GET request with OkHttp. The problem is that it throws an error and I don't know how to fix it even though I understand what the problem is.

I've tried replacing the character though it didn't work.

Code

    private static void checkMails() throws IOException, NoSuchAlgorithmException {
        // Set algorithm to MD5
        MessageDigest md = MessageDigest.getInstance("MD5");

        // Update the MessageDigest object with the bytes of our email.
        md.update("mail@dump.com".getBytes(StandardCharsets.UTF_8));

        // Digest the object which contains the bytes of our email String.
        byte[] digest = md.digest();

        // MD5 Hash of the email we generated using Details()
        String emailHash = DatatypeConverter
                .printHexBinary(digest).toLowerCase();
        // Get request which returns the response.
        String response = doGetRequest("https://privatix-temp-mail-v1.p.rapidapi.com/request/mail/id/" + emailHash + "/");
        System.out.println(emailHash);
        System.out.println(response);

        // If the response does contain mails then use the verify function.
        if (!response.contains("There are no emails yet")) {
            JSONObject json = new JSONObject(response);
            System.out.println(json.getString("mail_text"));
        } else {
            System.out.println("No mails yet.");
        }
    }


    /* GET Request method */
    private static String doGetRequest(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("x-rapidapi-host", "privatix-temp-mail-v1.p.rapidapi.com")
                .addHeader("x-rapidapi-key", config.getTempMailApiKey())
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

Data receieved from response:

[{"_id":{"oid":"5daf18a2f4a4b314d399d510"},"createdAt":{"milliseconds":1571756194861},"mail_id":"970af329d17a93669653b26bd7d1c779"

Error

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
    at org.json.JSONObject.<init>(JSONObject.java:222)
    at org.json.JSONObject.<init>(JSONObject.java:406)
    at creator.VerifyMail.checkMails(VerifyMail.java:51)
    at creator.VerifyMail.main(VerifyMail.java:27)

I expected to be able to convert it into a json object and then be able to get a specific part of the json object.

weq123qas
  • 5
  • 1
  • 2
    The data you receive is a JSON array, not a JSON object. So parse it as such. E.g. see https://stleary.github.io/JSON-java/org/json/JSONArray.html ; update: noticed that you use org.json so updated the link to that library's implementation of JSONArray. – Janus Varmarken Oct 22 '19 at 17:13
  • Your data is surrounded with [] which means it's an array as Janus stated. Seeing the library for `Response response` could be helpful, but I"m not going to dive in that far. – visch Oct 22 '19 at 17:15
  • Possible duplicate of [How to parse JSON Array (Not Json Object) in Android](https://stackoverflow.com/questions/18977144/how-to-parse-json-array-not-json-object-in-android) – Janus Varmarken Oct 22 '19 at 17:41

1 Answers1

0

I use the below method to verify a Random String is valid json. After Which i parse into appropriate object

    private static boolean isJson(String json) {
        Gson gson = new Gson();
        if(json.isEmpty()){
            return false;
        }
        try {
            gson.fromJson(json, Object.class);
            Object jsonObjType = gson.fromJson(json, Object.class).getClass();
            if(jsonObjType.equals(String.class)){
                return false;
            }
            return true;
        } catch (com.google.gson.JsonSyntaxException ex) {
            return false;
        }
    }
Akin Okegbile
  • 1,108
  • 19
  • 36