要从URL中解析JSON对象数组,首先需要理解几个基础概念:
HttpURLConnection
, Apache HttpClient
, 或者Java 11+中的java.net.http.HttpClient
。{}
包围,表示键值对的集合。[]
包围,表示值的有序列表。以下是使用Java 11+的HttpClient
和Gson库从URL解析JSON对象数组的示例代码:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
public class JsonParserExample {
public static void main(String[] args) {
String url = "https://example.com/api/data"; // 替换为实际的URL
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String jsonResponse = response.body();
Gson gson = new Gson();
Type listType = new TypeToken<List<MyJsonObject>>(){}.getType();
List<MyJsonObject> myJsonObjects = gson.fromJson(jsonResponse, listType);
// 处理解析后的对象数组
for (MyJsonObject obj : myJsonObjects) {
System.out.println(obj);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
// 假设JSON对象的结构如下
static class MyJsonObject {
private String id;
private String name;
// Getters, Setters, and toString method
@Override
public String toString() {
return "MyJsonObject{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
}
通过以上步骤和代码示例,可以从URL中成功解析JSON对象数组。如果遇到具体问题,可以根据错误信息进行调试和解决。
领取专属 10元无门槛券
手把手带您无忧上云