Java中如何原样获取带双引号的JSON请求体?
解决JSON字段双引号丢失问题
问题原因
你用Map<String, Object>接收JSON请求后,调用的toString()是Java集合的默认方法,输出的是键值对用等号连接的格式,并非标准JSON字符串,所以自然没有双引号。
解决方案
方案1:用JSON序列化工具将Map转为标准JSON
直接使用Jackson(JAX-RS生态常用的JSON处理库)把Map序列化为带双引号的标准JSON:
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("exportAssortmentTest") public Response exportAssortmentTest(@Context HttpHeaders headers, Map<String, Object> request) { if (request == null) { return Response.status(Response.Status.NOT_ACCEPTABLE) .cacheControl(null) .build(); } String pojoJson; try { // 初始化Jackson的ObjectMapper ObjectMapper mapper = new ObjectMapper(); // 先处理requestType的值:去掉下划线转为数字 if (request.containsKey("requestType")) { String rawValue = request.get("requestType").toString(); request.put("requestType", Integer.parseInt(rawValue.replace("_", ""))); } // 将Map序列化为标准JSON字符串 pojoJson = mapper.writeValueAsString(request); System.out.println("JSON: " + pojoJson); } catch (JsonProcessingException e) { // 处理序列化异常 return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } String jsonResponse = RSEStringUtils.EMPTY; return Response.ok(jsonResponse, MediaType.APPLICATION_JSON) .cacheControl(null) .build(); }
方案2:定义POJO接收请求(更规范)
创建对应请求结构的POJO类,让JAX-RS自动完成JSON解析,再序列化回标准JSON:
// 定义请求POJO public class AssortmentRequest { private String assortLabel; private String requestType; // Getter和Setter public String getAssortLabel() { return assortLabel; } public void setAssortLabel(String assortLabel) { this.assortLabel = assortLabel; } public String getRequestType() { return requestType; } public void setRequestType(String requestType) { this.requestType = requestType; } // 自定义序列化逻辑:处理requestType格式 @JsonGetter("requestType") public int getProcessedRequestType() { return Integer.parseInt(this.requestType.replace("_", "")); } }
修改接口方法:
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("exportAssortmentTest") public Response exportAssortmentTest(@Context HttpHeaders headers, AssortmentRequest request) { if (request == null) { return Response.status(Response.Status.NOT_ACCEPTABLE) .cacheControl(null) .build(); } String pojoJson; try { ObjectMapper mapper = new ObjectMapper(); pojoJson = mapper.writeValueAsString(request); System.out.println("JSON: " + pojoJson); } catch (JsonProcessingException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } String jsonResponse = RSEStringUtils.EMPTY; return Response.ok(jsonResponse, MediaType.APPLICATION_JSON) .cacheControl(null) .build(); }
说明
- 两种方案都能生成带双引号的标准JSON,可直接作为PL/SQL CLOB的输入。
- 若无需处理
requestType的格式转换,可去掉对应逻辑。
内容的提问来源于stack exchange,提问作者JDKTeam
相关产品推荐
相关产品推荐

