0

I am trying to create a test JSON validator in Java (on Fedora 27), but I cannot import JSON-related packages. Do different Java implementations use different packages for this purpose?
My source code is as follows:

import javax.json.JsonObject; 
import javax.json.JsonException;

public class JsonParsing {
    public static void Main(String[] args) {
        String str = "<h1>This is a test.</h1>";
        if(isValidJson(str)) {
               System.out.println("Valid JSON");
        }
        else {
            System.out.println("JSON Exception detected");
        }

    }
    private static boolean isValidJson(String response) {
        try{ 
        JSONObject jsonObj = new JSONObject (response);
        } catch(JSONException e) {
            System.out.println("JSONException");
            return false;
        }
        return true;
    }

}

Error log:

JsonParsing.java:2: error: package javax.json does not exist import javax.json.Json; ^ JsonParsing.java:3: error: package javax.json does not exist import javax.json.JsonObject; ^ JsonParsing.java:18: error: cannot find symbol JSONObject jsonObj = new JSONObject (response); ^ symbol:
class JSONObject location: class JsonParsing JsonParsing.java:18: error: cannot find symbol JSONObject jsonObj = new JSONObject (response); ^ symbol: class JSONObject location: class JsonParsing JsonParsing.java:19: error: cannot find symbol } catch(JSONException e) { ^ symbol: class JSONException location: class JsonParsing 5 errors

Mehdi Haghgoo
  • 3,144
  • 7
  • 46
  • 91

3 Answers3

2

include the following dependency in your "pom.xml" file.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
Nilamber Singh
  • 804
  • 1
  • 14
  • 33
  • Isn't this a different library for working with json? Doesn't the Java SDK library has its own json classes? – Tal Avissar Dec 14 '17 at 07:34
  • You can find your answer here.. https://stackoverflow.com/questions/3970195/is-it-possible-to-proccess-json-responses-with-the-jdk-or-httpcomponents-only – Nilamber Singh Dec 14 '17 at 07:47
1

The simple answer is, you don't have those classes in scope.

This package is not one of the standard java libraries included in your java environment, all you need to do is to find the required jar and ensure it is in scope.

MartinByers
  • 1,240
  • 1
  • 9
  • 15
0

The javax.json package is not part of Java SE. You can find the Java SE API for Java SE 9 at https://docs.oracle.com/javase/9/docs/api/overview-summary.html .

You need to add an additional library which implements the javax.json API to your classpath or module path. That JSON-P API was developed as part of JSR 353: https://jcp.org/en/jsr/detail?id=353 .

Dalibor Topic
  • 667
  • 7
  • 6