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

Gson toJson返回空对象及无法写入文件问题求助

解决Gson序列化UniShop返回空对象及写入文件失败问题

序列化空对象的核心原因及修复

Gson序列化返回空对象,通常是以下几个原因导致,按优先级排查:

  1. 缺少公共无参构造函数
    Gson依赖反射机制处理对象,即使序列化不强制要求无参构造,但缺少它可能导致字段无法被正确识别。给UniShop类添加公共无参构造是必要操作。

  2. 字段被transient/static修饰

    • transient标记的字段会被Gson直接忽略,不会参与序列化
    • static字段属于类而非对象,Gson默认不序列化静态字段
  3. 非静态内部类问题
    如果UniShop是某个类的非静态内部类,它会持有外部类的引用,Gson无法正常序列化这种结构,需要将其改为静态内部类或独立的顶级类。

正确的UniShop类示例

public class UniShop {
    private String shopName;
    private int shopId;
    private List<String> productList;

    // 必须的公共无参构造函数
    public UniShop() {}

    // 带参构造(用于初始化对象,可选)
    public UniShop(String shopName, int shopId, List<String> productList) {
        this.shopName = shopName;
        this.shopId = shopId;
        this.productList = productList;
    }

    // Getter/Setter(可选,但建议提供,不影响Gson序列化,但方便其他业务操作)
    public String getShopName() { return shopName; }
    public void setShopName(String shopName) { this.shopName = shopName; }
    public int getShopId() { return shopId; }
    public void setShopId(int shopId) { this.shopId = shopId; }
    public List<String> getProductList() { return productList; }
    public void setProductList(List<String> productList) { this.productList = productList; }
}

文件写入失败的修复

写入文件失败通常和路径、权限、流处理有关,以下是可靠的实现方式:

序列化+写入文件的完整代码

import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ShopSerializer {
    public static void main(String[] args) {
        // 初始化测试用的UniShop对象
        List<String> products = new ArrayList<>();
        products.add("笔记本");
        products.add("校园电话卡");
        UniShop myShop = new UniShop("东校区超市", 1001, products);

        // 序列化对象
        Gson gson = new Gson();
        String jsonStr = gson.toJson(myShop);
        System.out.println("序列化结果:" + jsonStr); // 先验证序列化是否正常

        // 写入文件,使用try-with-resources自动关闭流,避免资源泄漏
        String targetPath = "unishop_data.json"; // 可改为绝对路径,比如"D:/project/unishop.json"
        try (FileWriter writer = new FileWriter(targetPath)) {
            writer.write(jsonStr);
            System.out.println("文件写入成功,路径:" + targetPath);
        } catch (IOException e) {
            // 打印具体异常信息,方便排查
            System.err.println("写入失败:");
            e.printStackTrace();
        }
    }
}

文件写入问题排查

  • 路径错误:相对路径是相对于程序运行的工作目录(比如IDEA中是项目根目录),不确定的话直接用绝对路径
  • 权限不足:写入系统目录(如C盘根目录)需要管理员权限,建议写入项目内部的目录
  • 文件被占用:确保没有其他程序打开目标文件

内容的提问来源于stack exchange,提问作者Rémi-Antoine Joron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:17:31