无法将字符串转换为json对象

时间:2019-10-22 17:10:36

标签: java okhttp

我一直在尝试转换一个字符串,该字符串作为OkHttp的GET请求的响应而收到。问题是它引发了错误,即使我了解问题所在,我也不知道如何解决。

我尝试替换字符,尽管它不起作用。

代码

    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();
    }

从响应中收到数据:

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

错误

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)

我希望能够将其转换为json对象,然后能够获取json对象的特定部分。

1 个答案:

答案 0 :(得分:0)

我使用以下方法来验证随机字符串是有效的json。之后,我解析为适当的对象

    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;
        }
    }