You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gson反序列化静态字段返回null:无法获取JSON中的url值

解决Gson反序列化NASA APOD JSON时url字段为null的问题

问题描述

使用Gson反序列化NASA APOD接口返回的JSON数据时,提取url字段始终得到null值,预期能正确获取该字段对应的URL地址。

JSON示例

{
  "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"
}

现有代码

Output类

package space;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;

import com.google.gson.Gson;

public class Output {

    public static void main(String input) throws IOException, InterruptedException, URISyntaxException {
        if (input == "news") {
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest 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);
        }
    }
}

Objects类

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;
    }
}

问题原因分析

  1. 静态字段无法被Gson自动映射:Objects类中的url字段被声明为static,Gson默认只会处理实例字段,不会自动赋值静态字段。
  2. Setter方法不匹配:现有Setter方法名为sethdurl,对应JSON中的hdurl字段,而非url字段,Gson无法找到url对应的Setter来赋值。
  3. Getter方法不符合规范:geturl是静态方法,Gson在反序列化时操作的是实例对象,无法通过静态方法获取实例字段的值。
  4. 字符串比较错误:input == "news"使用引用比较,而非值比较,可能导致逻辑分支无法进入(虽非url为null的直接原因,但属于代码隐患)。

修复方案

1. 修正Objects类,遵循JavaBean规范

将url改为实例字段,提供与JSON字段名匹配的Getter和Setter方法:

package space;

public class Objects {
    private String url;

    // 匹配JSON的url字段,提供Getter
    public String getUrl() {
        return url;
    }

    // 提供对应的Setter,Gson会自动调用该方法赋值
    public void setUrl(String url) {
        this.url = url;
    }
}

若希望保留原方法名geturl,Gson也能兼容,但建议使用符合JavaBean规范的驼峰命名(getUrl/setUrl)。

2. 修正Output类中的字符串比较

将引用比较改为值比较:

if ("news".equals(input)) {
    // 原有逻辑
}

验证结果

修复后重新运行代码,Gson会正确将JSON中的url字段值映射到Objects实例的url字段,调用getUrl()(或geturl())即可获取到正确的URL地址。

内容的提问来源于stack exchange,提问作者Rose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:30:51