You need to enable JavaScript to run this app. Java使用Gson解析嵌套JSON转Map<Request,Response>的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Java使用Gson解析嵌套JSON转Map<Request,Response>的实现方法

前置自定义类调整

Request类

需要补充无参构造、重写equals()和hashCode()(作为Map键必须实现,否则相同内容的请求会被识别为不同键):

import java.util.Map;
import java.util.Objects;

public class Request {
    private String url;
    private Map<String, String> headers;
    private String body;
    private String method;

    // Gson反序列化必须的无参构造
    public Request() {}

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Request request = (Request) o;
        return Objects.equals(url, request.url) 
                && Objects.equals(headers, request.headers) 
                && Objects.equals(body, request.body) 
                && Objects.equals(method, request.method);
    }

    @Override
    public int hashCode() {
        return Objects.hash(url, headers, body, method);
    }

    // 可选:重写toString方便调试输出
    @Override
    public String toString() {
        return "Request{url='" + url + "', method='" + method + "'}";
    }
}

Response类

补充无参构造、可选的getter方法方便取值:

public class Response {
    private String body;
    private int code;

    // Gson反序列化必须的无参构造
    public Response() {}

    public String getBody() {
        return body;
    }

    public int getCode() {
        return code;
    }
}

实现方案

方案1:适配现有Object[]读取逻辑

适合你已经写出Object[] obj = gson.fromJson(...)代码的场景,不需要调整原有读取流程,直接从现有结果中提取转换:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ParseDemo {
    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        Object[] objArray = gson.fromJson(new FileReader("myJson.json"), Object[].class);
        
        Map<Request, Response> resultMap = new HashMap<>();
        
        for (Object item : objArray) {
            // 将单个数组元素(对应JSON里的{request:xxx, response:xxx}对象)转成Map
            Map<String, Object> itemMap = gson.fromJson(
                    gson.toJson(item),
                    new TypeToken<Map<String, Object>>(){}.getType()
            );
            
            // 提取request字段,转成自定义Request类
            Request req = gson.fromJson(gson.toJson(itemMap.get("request")), Request.class);
            // 提取response字段,转成自定义Response类
            Response resp = gson.fromJson(gson.toJson(itemMap.get("response")), Response.class);
            
            resultMap.put(req, resp);
        }

        // 验证输出
        for (Map.Entry<Request, Response> entry : resultMap.entrySet()) {
            System.out.println("请求:" + entry.getKey());
            System.out.println("响应状态码:" + entry.getValue().getCode());
        }
    }
}

方案2:更规范的直接映射方式

新增一个中间DTO类,直接对应JSON数组的单个元素结构,不需要手动拆Map,代码更简洁容错性更高:

  1. 新增中间类RequestResponsePair:
public class RequestResponsePair {
    private Request request;
    private Response response;

    public RequestResponsePair() {}

    public Request getRequest() {
        return request;
    }

    public Response getResponse() {
        return response;
    }
}
  1. 直接读取转换为目标Map:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParseDemo {
    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        // 直接把整个JSON数组映射为List<RequestResponsePair>
        List<RequestResponsePair> pairList = gson.fromJson(
                new FileReader("myJson.json"),
                new TypeToken<List<RequestResponsePair>>(){}.getType()
        );

        Map<Request, Response> resultMap = new HashMap<>();
        for (RequestResponsePair pair : pairList) {
            resultMap.put(pair.getRequest(), pair.getResponse());
        }
    }
}

注意事项
  • 所有自定义类必须补充无参构造方法,否则Gson反序列化时会抛出异常
  • Request作为Map的键,必须重写equals()和hashCode(),否则相同内容的请求会被识别为不同对象,导致Map存入重复条目、后续查询匹配失败
  • 若JSON中存在自定义类未定义的字段(比如示例中Response未定义headers字段),Gson默认会自动忽略多余字段,无需额外配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 14:36:08