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

如何将指定JSON转换为可访问的Java对象(基于GSON库)

用GSON映射嵌套JSON到Java实体类并编辑键值

首先先修正你提供的JSON语法错误:第二个systems元素里的"name": "string"末尾缺少逗号,修正后才能正常解析:

{
    "title": "Application Title <You may change the title of your app>",
    "description": "This is an inventory for company system information",
    "systems": [
        {
            "name": "string",
            "purpose": "string",
            "owner": "string",
            "sub_owner": ["string", "string"],
            "location": "string",
            "tag": "string"
        },
        {
            "name": "string",
            "purpose": "string",
            "owner": "string",
            "sub_owner": ["string", "string"],
            "location": "string",
            "tag": "string"
        }
    ]
}

步骤1:创建匹配JSON结构的Java实体类

不要用Map<String, Object>处理嵌套结构,直接创建和JSON字段一一对应的实体类,类型安全且操作方便:

顶层实体类 AppInventory

import java.util.List;

public class AppInventory {
    private String title;
    private String description;
    private List<SystemInfo> systems;

    // 生成Getter和Setter方法
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    public List<SystemInfo> getSystems() { return systems; }
    public void setSystems(List<SystemInfo> systems) { this.systems = systems; }
}

嵌套实体类 SystemInfo

import java.util.List;

public class SystemInfo {
    private String name;
    private String purpose;
    private String owner;
    private List<String> sub_owner;
    private String location;
    private String tag;

    // 生成Getter和Setter方法
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getPurpose() { return purpose; }
    public void setPurpose(String purpose) { this.purpose = purpose; }

    public String getOwner() { return owner; }
    public void setOwner(String owner) { this.owner = owner; }

    public List<String> getSub_owner() { return sub_owner; }
    public void setSub_owner(List<String> sub_owner) { this.sub_owner = sub_owner; }

    public String getLocation() { return location; }
    public void setLocation(String location) { this.location = location; }

    public String getTag() { return tag; }
    public void setTag(String tag) { this.tag = tag; }
}

步骤2:用GSON解析JSON并编辑属性

现在可以直接将JSON解析为实体类对象,轻松访问和修改任意层级的属性:

import com.google.gson.Gson;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class JsonHandler {
    public static void main(String[] args) throws Exception {
        // 读取JSON文件
        String jsonData = new String(Files.readAllBytes(Paths.get("Java/system.json")));

        // 解析为实体类对象
        Gson gson = new Gson();
        AppInventory inventory = gson.fromJson(jsonData, AppInventory.class);

        // 1. 修改顶层属性
        inventory.setTitle("Updated Company System Inventory");
        inventory.setDescription("This is an updated inventory tracking company IT systems");

        // 2. 修改嵌套的systems列表中的属性
        List<SystemInfo> systems = inventory.getSystems();
        // 修改第一个系统的名称
        systems.get(0).setName("HR Management System");
        // 修改第一个系统的子负责人列表
        systems.get(0).getSub_owner().set(0, "Alice Smith");
        systems.get(0).getSub_owner().add("Bob Johnson");

        // 修改第二个系统的位置
        systems.get(1).setLocation("Data Center 2");

        // 可选:将修改后的对象写回JSON文件
        String updatedJson = gson.toJson(inventory);
        Files.write(Paths.get("Java/updated_system.json"), updatedJson.getBytes());

        // 打印验证修改结果
        System.out.println("Updated Title: " + inventory.getTitle());
        System.out.println("First System Name: " + systems.get(0).getName());
        System.out.println("First System Sub Owners: " + systems.get(0).getSub_owner());
    }
}

为什么不用Map方式?

  • Map<String, Object>需要频繁强制类型转换(比如把systems对应的Object转成List<Map<String, Object>>),代码繁琐且容易出现类型转换异常。
  • 实体类具备类型安全,IDE会自动提示属性名,避免拼写错误,同时代码可读性和维护性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:30:50