Solved How to check if string is a valid json?

Discussion in 'Spigot Plugin Development' started by DrOreo002, Jul 4, 2018.

Thread Status:
Not open for further replies.
  1. Title say it all ;)

    Btw this is what I've tried, and it seems like its not working
    Code (Text):
    public static boolean isJson(String jsonInString) {
            try {
                gson.fromJson(jsonInString, Object.class);
                return true;
            } catch(com.google.gson.JsonSyntaxException ex) {
                return false;
            }
        }
     
  2. Your idea is correct. I think it's not working because you gave as a type the Object type that is general. Try to put Map type instead. I'm not sure it'll work but just try.
    However, why do you need to check if a string is a json parsable?
     
  3. Code (Text):
    public boolean isValid(String test) {
       try {
           new JSONObject(test);
       } catch (JSONException ex) {
           try {
               new JSONArray(test);
           } catch (JSONException ex1) {
               return false;
           }
       }
       return true;
    }
     
    • Like Like x 2
    • Agree Agree x 2
    • Useful Useful x 1
  4. Seems like I cannot find the JSOnException class, what do I need to import?

    json'.png
     
  5. That's weird. It's part of json simple, which is shaded into the Bukkit API..

    I wonder if Google's version is watered down or something..

    You can get the official version from this maven repo.
     
  6. Hmm, I'm using spigot as a dependency here. Is it because of that?

    Btw if I use that maven repo on my plugin, it makes a noClassDefFound error (ofc). So what can I do?
     
  7. Might be. Add the API too (API above implementation). In fact, you should already be doing this to avoid the ambiguous issues mentioned in that thread.
     
  8. Do you mean bukkit?
     
  9. I just checked it and Spigot does not include org.json within their maven dependency, you would have to use this.
    Code (Text):
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
    </dependency>
     
    Spigot only comes with org.json.simple which do not have the JSONException.
     
  10. But it makes an noClassDefFound error on my plugin :/
     
  11. Do you shade json within the jar?
     
  12. Soo I need to shade it?, well lemme try
     
  13. Code (Java):
    public static boolean isValidJson(String json) {
        try {
            return new JsonParser().parse(json).asJsonObject() != null;
        } catch (Throwable ignored) {}
        return false;
    }
    Should work with Gson
     
    • Useful Useful x 1
  14. Hey, ty for that!. Its forking fine ;). Also shading the api is working but this code is working fine and no need to shade some api, etc.

    Ty guys for da help. I'll close this and mark it as solved
     
Thread Status:
Not open for further replies.