我正在尝试完成一个学校项目,该项目要求我从 API 收集数据。我能够连接到 API 并收集 JSON 文件中的数据。然后我尝试解析数据,并遇到了一个问题:我的 JSON 文件有许多带有对象的数组,反之亦然。我试图找到一种方法来隔离“日期”和“值”部分,但我陷入了困境。我正在尝试遵循本教程:https://androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial/.
但是,我无法使用
org.json
依赖项中的任何内容,例如 getJSONObject
。
我遇到了该依赖项的“路径损坏”错误,但我尝试了一下,它不再显示错误,但它仍然无法正常工作
错误:
Cannot resolve method 'getJSONObject' in 'JSONObject'
我的依赖:
我要解析的内容:
{"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}]}]}]}
我的代码:
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();
}
}
}
这是我的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>
如果有办法以不同的方式解析它或修复依赖问题,请告诉我!
在互联网上寻找一些帮助,但没有一个教程有帮助,我尝试重新启动但没有运气。我还尝试将 jar 添加到我的库中。
您的 getJSONObject 方法仍未解决的原因是因为您混合了两个不同的 JSON 库:org.json 和 json-simple。
您需要使用 org.json 库或 json-simple 进行 JSON 解析,并确保一致使用所选的库。 json-simple 库不提供像 getJSONObject 这样的方法。
在我看来,您应该完全使用 org.json 进行解析,因为您已经将其添加为依赖项。
您可以修改代码以使用 org.json 库,例如:
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();
}
}
}
代码现在将使用 org.json.JSONObject 和 org.json.JSONArray 来解析您的 json。
然后,代码浏览 JSON 结构,提取“数据”,然后提取“坐标”,最后提取“日期”数组以获取“日期”和“值”。
确保您在 pom.xml 中正确设置了 org.json 依赖项,我可以看到您已经这样做了。
如果解决依赖关系的问题仍然存在,请尝试重建项目或在 IDE 中重新导入 Maven 依赖关系。