Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

How do I validate a JSON string in Java? Or could I parse it using regular expressions?

1 Answer

0 votes
by (46k points)

A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {

    try {

        new JSONObject(test);

    } catch (JSONException ex) {

        // edited, to include @Arthur's comment

        // e.g. in case JSONArray is valid as well...

        try {

            new JSONArray(test);

        } catch (JSONException ex1) {

            return false;

        }

    }

    return true;

}

This code uses org.json JSON API implementation that is available on githubin maven and partially on Android.

Related questions

0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)

Browse Categories

...