序列化和反序列化具有相同名称的 Jackson XML 元素

我正在尝试编写代码和对象来使用类反序列化 XML,如下所示Product:


<list>

  <product id="14032019"><![CDATA[Some text]]></product>

  <product id="14032019" value="Some text"/>

</list>

Product POJO 具有注释如下的 value 属性,它适用于这些情况:


<product id="14032019" value="Some text"/>:


@JacksonXmlProperty(isAttribute = true)

private String value; 

<product id="14032019"><![CDATA[Some text]]></product>:


@JacksonXmlCData

@JacksonXmlText

private String value; 

但当我组合所有注释时,它似乎不起作用。有人遇到过这样的问题吗?


编辑:


我尝试使用从父类继承并单独标识的 2 个不同子类进行注释(我按照https://www.baeldung.com/jackson-annotations@JsonSubTypes中的示例进行操作)。此方法需要在 XML 中为每个标记调用一个属性,而原始 XML 中未提供该属性。className


<product className="myPackage.Product1" id="123" value="Some text"/>

<product className="myPackage.Product2" id="123">Some text</product>

对于没有 className 属性的情况,是否可以编写自定义映射器或反序列化器?


holdtom
浏览 112回答 1
1回答

汪汪一只猫

该解决方案背后的想法是实现一个特定的解串器。public class ProductDeserializer extends StdDeserializer<Product> {&nbsp; public ProductDeserializer() {&nbsp; &nbsp; &nbsp; super(Product.class);&nbsp; }&nbsp; @Override&nbsp; public Product deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {&nbsp; &nbsp; Product p = new Product();&nbsp; &nbsp; while (parser.nextToken() != JsonToken.END_OBJECT) {&nbsp; &nbsp; &nbsp; &nbsp; String tokenName = parser.getCurrentName();&nbsp; &nbsp; &nbsp; &nbsp; switch (tokenName) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "id":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parser.nextToken();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p.setId(parser.getText());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // when you encounter an attribute called value or "" you take its value&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "value":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parser.nextToken();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p.setValue(parser.getText().trim());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return p;&nbsp; }}当你使用该类时,你必须注册它XmlMapper:XmlMapper xmlMapper = new XmlMapper();SimpleModule module = new SimpleModule("configModule", Version.unknownVersion());module.addDeserializer(Product.class, new ProductDeserializer());xmlMapper.registerModule(module)产品 POJO 具有 id 和 value 作为属性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java