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

Java Spring Boot中如何动态生成JSON/XML请求体替代硬编码字符串

方案1:基于POJO的序列化实现(最推荐)

Spring Boot默认集成Jackson序列化库,同时支持JSON和XML格式的序列化/反序列化,不需要手动拼接字符串,可通过配置自动忽略空字段,完美适配非必填字段按需传递的需求。

JSON请求处理

  • 先定义对应请求结构的POJO类,通过注解配置序列化规则:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

// 序列化时自动忽略所有null值字段
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class JsonRequest {
    private String field1;
    private String field2;
    private String field3;
    private Integer field4;
    // 此处省略getter、setter、无参构造方法
}
  • 调用时仅需给需要传递的字段赋值,RestTemplate会自动完成序列化:
// 仅设置需要传递的字段,未设置的null字段不会被序列化到请求体中
JsonRequest jsonRequest = new JsonRequest();
jsonRequest.setField1(myString1);
jsonRequest.setField2(myString2);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<JsonRequest> request = new HttpEntity<>(jsonRequest, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<MyResponseClass> response = restTemplate.postForEntity(url, request, MyResponseClass.class);

XML请求处理

  • 引入Jackson XML扩展依赖(Spring Boot新版web依赖已默认集成,未集成的话手动引入即可),定义XML结构对应的POJO:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.annotation.JsonInclude;

// 配置XML根节点名称,自动忽略null值字段
@JacksonXmlRootElement(localName = "input")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class XmlRequest {
    private String input1;
    private String input2;
    // 此处省略getter、setter、无参构造方法
}
  • 调用逻辑和JSON场景完全一致,仅需修改Content-Type:
XmlRequest xmlRequest = new XmlRequest();
xmlRequest.setInput1(myString1);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<XmlRequest> request = new HttpEntity<>(xmlRequest, headers);
ResponseEntity<MyResponseClass> response = restTemplate.postForEntity(url, request, MyResponseClass.class);
方案2:基于动态Map的实现(无需定义POJO场景)

如果请求结构非常灵活,不想单独维护POJO类,可直接用Map封装需要传递的字段,Jackson同样支持直接序列化Map为对应格式:

// JSON场景示例
Map<String, Object> requestMap = new HashMap<>();
requestMap.put("field1", myString1);
requestMap.put("field4", 100);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestMap, headers);
// XML场景示例
XmlMapper xmlMapper = new XmlMapper();
Map<String, Object> requestMap = new HashMap<>();
requestMap.put("input1", myString1);
// 手动指定根节点名称,序列化得到XML字符串
String xmlBody = xmlMapper.writer().withRootName("input").writeValueAsString(requestMap);
HttpEntity<String> request = new HttpEntity<>(xmlBody, headers);

以上方案所有的格式校验、特殊字符转义都由序列化框架自动处理,完全避免字符串拼接导致的格式错误、转义错误问题,可维护性大幅提升。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:06:04