【发布时间】:2022-12-11 12:59:01
【问题描述】:
我正在尝试从这个 json 中获取 hdurl:
{
"date": "2022-12-08",
"explanation": "A camera on board the uncrewed Orion spacecraft captured this view on December 5 as Orion approached its return powered flyby of the Moon. Below one of Orion's extended solar arrays lies dark, smooth, terrain along the western edge of the Oceanus Procellarum. Prominent on the lunar nearside Oceanus Procellarum, the Ocean of Storms, is the largest of the Moon's lava-flooded maria. The lunar terminator, shadow line between lunar night and day, runs along the left of the frame. The 41 kilometer diameter crater Marius is top center, with ray crater Kepler peeking in at the edge, just right of the solar array wing. Kepler's bright rays extend to the north and west, reaching the dark-floored Marius. Of course the Orion spacecraft is now headed toward a December 11 splashdown in planet Earth's water-flooded Pacific Ocean.",
"hdurl": "https://apod.nasa.gov/apod/image/2212/art001e002132.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Orion and the Ocean of Storms",
"url": "https://apod.nasa.gov/apod/image/2212/art001e002132_apod1024.jpg"
}
我的代码是:
package space;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Paths;
import com.google.gson.Gson;
import java.net.http.HttpResponse.BodyHandlers;
public class Output {
public static void main(String input) throws IOException, InterruptedException, URISyntaxException {
if (input == "news") {
HttpClient client = HttpClient.newHttpClient();
HttpRequest getRequest;
getRequest = HttpRequest.newBuilder()
.uri(new URI("https://api.nasa.gov/planetary/apod?api_key=vtBLyZ1ON5hZybof2EfuXHWgdcNAXh9DdZrZAOvK")) //Demo key, (replace later)
.build();
HttpResponse<String> response = client.send(getRequest, BodyHandlers.ofString());
System.out.println(response.body());
Objects ojkn = new Objects();
Gson gson = new Gson();
ojkn = gson.fromJson(response.body(),Objects.class);
String result = ojkn.geturl();
System.out.println(result);
}
}
}
这是我的对象文件:
package space;
public class Objects {
private static String url;
public static String geturl() {
return url;
}
public void sethdurl(String url) {
Objects.url=url;
}
public Object get(String string) {
return null;
}
}
我的代码应该告诉我完整的 json,然后我只想获取链接 url ,但我得到的链接是空的。
【问题讨论】:
标签: java json gson httpclient