JAVA解析xml注解@JacksonXmlRootElement

本文介绍了如何使用Jackson库中的`@JacksonXmlRootElement`和`@JacksonXmlProperty`注解来解析XML字符串到Java对象。通过引入`jackson-dataformat-xml`依赖,并配置`ObjectMapper`忽略未知属性,可以方便地将XML字符串转换为`XmlResult`类实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事例: 

@JacksonXmlRootElement(localName = "xml")
public class XmlResult {

    @JacksonXmlProperty(localName = "InfoType")
    private String infoType;
}

引入包 

<!-- jackson序列化反序列化xml数据格式 -->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

调用

ObjectMapper mapper = new XmlMapper();
//忽略实体类中不含有的字段方法
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//xmlString为需要解析的xml字符串,XmlResult 为使用了注解的DTO类
XmlResult xmlResult = mapper.readValue(xmlString, XmlResult.class);

 

package com.example.demo.config; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // ObjectMapper objectMapper = JsonMapper.builder() MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); jsonConverter.setObjectMapper(new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)); jsonConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"))); MappingJackson2XmlHttpMessageConverter xmlConverter = new MappingJackson2XmlHttpMessageConverter(); xmlConverter.setObjectMapper(new XmlMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)); xmlConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XML, new MediaType("application", "*+xml"))); converters.add(jsonConverter); converters.add(xmlConverter); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer .mediaType("json", MediaType.APPLICATION_JSON) .mediaType("xml", MediaType.APPLICATION_XML); } @Bean public ContentNegotiationManager contentNegotiationManager() { ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); factory.setDefaultContentType(MediaType.APPLICATION_JSON); factory.setFavorParameter(true); factory.setParameterName("format"); factory.setIgnoreAcceptHeader(true); factory.setUseRegisteredExtensionsOnly(true); Map<String, MediaType> mediaTypes = new HashMap<>(); mediaTypes.put("json", MediaType.APPLICATION_JSON); mediaTypes.put("xml", MediaType.APPLICATION_XML); factory.addMediaTypes(mediaTypes); return factory.getObject(); } } package com.luxsan.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * 校验结果封装类 */ @Data @AllArgsConstructor @NoArgsConstructor @JacksonXmlRootElement(localName = "validationResult") public class ValidationResult { @JsonProperty("checkType") private String checkType; // 检查类型: FIELD/REGEX/NUMERIC @JsonProperty("fieldName") private String fieldName; // 字段名 @JsonProperty("expected") private String expected; // 预期值 @JsonProperty("actual") private String actual; // 实际值 @JsonProperty("valid") private boolean valid; // 是否通过 } @PostMapping(value = "/compare") public R compare(@RequestPart("File") MultipartFile file, @RequestPart("jsonContent") String jsonContent) { //读取PDF文本 String pdfText = compareService.extractContent(file); //解析JSON配置 JsonNode jsonConfig = null; try { jsonConfig = compareService.parseJson(jsonContent); } catch (Exception e) { return R.fail(MessageUtils.message("failed.convert.json")); } //执行对比校验 List<ValidationResult> results = compareService.compareContent(pdfText, jsonConfig); //返回没有匹配成功的数据 List<ValidationResult> failedResults = new ArrayList<>(); for (ValidationResult result : results) { if (!result.isValid()) { failedResults.add(result); } } if (failedResults.isEmpty()) { return R.ok("条件符合规范"); } else { return R.ok(failedResults); } } 我的xml结果还是json { "code": 200, "msg": "sys.option.success", "data": [ { "checkType": "FIELD", "fieldName": "modelNo", "expected": "A2676", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "gtin", "expected": "04549995463484", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "product", "expected": "MW2K3AM/A", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "sscc18", "expected": "101959490980003121", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "count", "expected": "10", "actual": "Not Found", "valid": false }, { "checkType": "FIELD", "fieldName": "s1", "expected": "(02)04549995463484(37)10", "actual": "Not Found", "valid": false } ] }
最新发布
07-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值