Search code examples
javajsonmaven

InteliJ project not recognizing org.json dependency, cant use getJSONObject or jsonObject


I'm trying to complete a school project that has me collecting data from an API. I was able to connect to the API and collect the data in a JSON file. I then attempted to parse the data, and ran into the issue that my JSON file had many arrays withing objects and vice versa. I'm trying to figure out a way to isolate just the "date" and "value" portions but I'm very stuck. I'm trying to follow this tutorial: https://androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial/.

However, I cant use anything from the org.json dependency like getJSONObject.

I had a "broken path" error for that dependency, but I played around with it and it's no longer showing the error, but its still not working

The error: Cannot resolve method 'getJSONObject' in 'JSONObject'

My dependencies:

enter image description here

What I'm trying to parse:


{"version":"3.0","user":"valenciacollege_rivera_christina","dateGenerated":"2024-10-20T09:21:40Z","status":"OK","data":[{"parameter":"t_2m:C","coordinates":[{"lat":52.520551,"lon":13.461804,"dates":[{"date":"2024-10-20T00:00:00Z","value":11.3}]}]}]}

My code:

package org.example;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.json.*;




public class Test3 {
    public static void main(String[] args) throws Exception {
        try {

            File file = new File("filename.json");
            try {
                File myObj = new File("filename.json");
                if (myObj.createNewFile()) {
                    System.out.println("File created: " + myObj.getName());
                } else {
                    System.out.println("File already exists.");
                }
            } catch (IOException e) {
                System.out.println("An error occurred.");
                e.printStackTrace();
            }
            //  String username = args[0];
            //  String password = args[1];

            // System.out.print("username: " + username + ", password: " + password + "\n");

            URI uri = new URI("https://api.meteomatics.com/2024-10-20T00:00:00Z/t_2m:C/52.520551,13.461804/json");
            URL url = uri.toURL();
            String credentials = "valenciacollege_rivera_christina" + ":" + "VV2hU5du3q";
            String encoding = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Authorization", "Basic " + encoding);

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader streamReader = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }

            System.out.print(responseStrBuilder.toString());

            //try
            FileWriter myWriter = new FileWriter("filename.json");
            myWriter.write(String.valueOf(responseStrBuilder));
            myWriter.close();

            //super try JSON PARSING
            Object obj = new JSONParser().parse(new FileReader("filename.json"));
            JSONObject jo = (JSONObject) obj;



            JSONArray ja = (JSONArray) jo.get("data");
            System.out.println("DATA HERE:" + ja);

            JSONObject obj2= jo.getJSONObject("data"); //getJSONObject is red
            


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}

Here is my pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SoilTemp1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>22</maven.compiler.source>
        <maven.compiler.target>22</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.open-meteo</groupId>
            <artifactId>sdk</artifactId>
            <version>1.10.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20240303</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>


    </dependencies>

</project>

If there's a way to parse this differently or fix the dependency issue, please let me know!

Looked around the internet for some help, but none of the tutorials helped, I tried restarting and no luck. I also tried adding the jar to my library.


Solution

  • The reason why your getJSONObject method remains unresolved is because you're mixing two different JSON libraries: org.json and json-simple.

    You need to use either the org.json library or json-simple for your JSON parsing and make sure to use the chosen library consitently. The json-simple library does not provide methods like getJSONObject.

    In my opinion, you should entirely use the org.json for parsing, as you have already added it as a dependency.

    You can modify your code to use the org.json library like:

    import java.io.*;
    import org.json.JSONArray;
    import org.json.JSONObject;
    import java.net.HttpURLConnection;
    import java.net.URI;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    
    public class Test3 {
        public static void main(String[] args) {
            try {
                // Connect to your API
                URI uri = new URI("https://api.meteomatics.com/2024-10-20T00:00:00Z/t_2m:C/52.520551,13.461804/json");
                URL url = uri.toURL();
                String credentials = "valenciacollege_rivera_christina" + ":" + "VV2hU5du3q";
                String encoding = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
    
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("Authorization", "Basic " + encoding);
    
                if (conn.getResponseCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                }
    
                // Read the response as below
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder responseStrBuilder = new StringBuilder();
                String inputStr;
                while ((inputStr = streamReader.readLine()) != null) {
                    responseStrBuilder.append(inputStr);
                }
    
                // Now parse your JSON response using org.json
                JSONObject jsonResponse = new JSONObject(responseStrBuilder.toString());
    
                // Extract the data array from the JSON
                JSONArray dataArray = jsonResponse.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject dataObject = dataArray.getJSONObject(i);
                    JSONArray coordinatesArray = dataObject.getJSONArray("coordinates");
                    
                    // Next, loop through coordinates to get the date and value
                    for (int j = 0; j < coordinatesArray.length(); j++) {
                        JSONObject coordinate = coordinatesArray.getJSONObject(j);
                        JSONArray datesArray = coordinate.getJSONArray("dates");
    
                        for (int k = 0; k < datesArray.length(); k++) {
                            JSONObject dateObject = datesArray.getJSONObject(k);
                            String date = dateObject.getString("date");
                            double value = dateObject.getDouble("value");
    
                            // Output the date and value
                            System.out.println("Date: " + date + ", Value: " + value);
                        }
                    }
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    The code will now use org.json.JSONObject and org.json.JSONArray for parsing your json.

    The code then navigates through the JSON structure, and extracts "data", then "coordinates", and finally the "dates" array to get the "date" and "value".

    Make sure you have the org.json dependency properly set up in your pom.xml, which I can see you already do.

    If the issue with resolving dependencies still persists, try rebuilding the project or re-importing the Maven dependencies in your IDE.