FasterXML / FasterXML/jackson-dataformat-xml

XML attributes are not correctly populated when converting from XML (ObjectNode) to String using writeValueAsString (XML structure)

Aperta
#613 3 commenti 1 reazione 0 assegnatari Vedi su GitHub
Lingua principale
Java
Stelle
631
Fork
246
Merge medio
7g 9h
PR unite (30g)
13

Descrizione

Hi @cowtowncoder,

We are planning to migrate our old deserialization logic from using fragmented substrings between `` and `` tags when deserializing an XML String to POJOs into Jackson’s sophisticated custom `StdDeserializers/JsonDeserializers` directly starting from version `2.15.2`.

I have a few questions about whether this feature of mine already exists or not.

My team and I are trying to deserialize a very complex XML structure, to the point that we do not have to create multiple beans because some of the content of our XML subtree often changes dynamically with minimal format structure (we have `~10 XML formats` to support with or without attributes and namespaces) and is also a valid XML structure. WE mostly used custom deserializers like `StdDeserializer` and `JsonDeserializer` to map `ObjectNode` into plain `Map` (well internally, this is already a `Map`) (thanks for your suggestion in #574) and then later converted it back to String.

While I still stumbled across our implementation to keep our XML subtree to be deserialized via substring. But then later we planned to stick to using `JsonNode` to retrieve segments of XML and convert it back to the original XML as String using `SegmentedStringWriter#writeValueAsString`, for a reason that we wanted to leverage the `java.xml.stream.*` without the need to retrieve full string token and to fully adapt `Jackson's Streaming API` interoperability. We do not want to convert it into a plain POJO, but instead, would rather use the `java.util.Map` class to keep it generic and to store every `JsonNode` token retrieved from `ObjectNode#getValue()`.

## Sample Scenario
Supposedly, I have an XML element that contains an attribute `name` and `age`.
```XML

woof woof!
meowwwwwww!
cluck cluck!
oink oink!

```
## XML Attribute
The output I would expect should be the same as the original XML, but in my case, it's not:
```XML


tucker
2
<>woof woof!


cody
2
<>meowwwwwww!


browny
3
<>cluck cluck cluck cluck!


porky
4
<>oink oink!

```
The attributes became sub-elements of the original element, while the element tag of the original element value becomes empty: `<>...`

## XML Namespace
The same happens with namespaces:
suppose Animal namespace declaration: ``

Output:
```XML

urn:this:is:namespace:for:animal

tucker
2
<>woof woof!

```
The namespace becomes a new element.

###
My assumption is that it will only work with a plain XML structure (excluding the attributes itself) or with bean-defined POJOs annotated XML attr properties.

## Sampe Driver Code
Tried using custom XmlMapper config:
```java
private static XMLInputFactory xmlInputFactory() {
final XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
return factory;
}

OBJECT_WRITER = new XmlMapper(xmlInputFactory(), customJacksonXmlModule())
.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true)
.enable(SerializationFeature.INDENT_OUTPUT)
.writer();

```

```java
JsonNode node = mapper.readTree(
"\n"
+ " woof woof!\n"
+ " meowwwwwww!\n"
+ " cluck cluck!\n"
+ " oink oink!\n"
+ " ");

System.out.println(mapper.writer().withDefaultPrettyPrinter().withRootName("animal").writeValueAsString(node));
```

and with a custom deserializer for the `Animal` bean.
```java
@JsonDeserialize(using = AnimalDeserializer.class)
class Animal {
String xmlContent; // <-- JsonNode to String: woof woof!...
}
```

### AnimalDeserializer.java
```java
@Override
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
final ObjectCodec codec = parser.getCodec();
final ObjectNode objectNode = codec.readTree(parser);

final T object = codec.readValue(objectNode.traverse(), getValueType(context));
final Iterator> nodeIterator = objectNode.fields();

while (nodeIterator.hasNext()) {
Entry nodeEntry = nodeIterator.next();
// we manually set the value for non-annotated @JsonProperty() fields, let Jackson take care for us!!
if (!attributes().contains(nodeEntry.getKey())) {
if (nodeEntry.getValue() instanceof ObjectNode) {
object.setContent(readObjectNodeAsString(nodeEntry));
}
...
}
}

return object;
}

private String readObjectNodeAsString(Entry nodeEntry) {
try {
return OBJECT_WRITER
.withRootName(nodeEntry.getKey())
.writeValueAsString(nodeEntry.getValue());
}
...
}
```

## Update:
When using `TypeReference(){}`, it prints the expected XML output. However, the attribute is still missing.

```Java
Map node = XML_MAPPER.readValue("...", new TypeReference>() {});
```

Output:
```XML

woof woof!
meowwwwwww!
...
```

We really appreciate your feedback and suggestions for this @cowtowncoder

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Direzione di ricerca

Inizia con il driver di esempio che usa XmlMapper.readTree e writeValueAsString, quindi esamina il file AnimalDeserializer.java personalizzato e il relativo metodo readObjectNodeAsString. Confronta l’ObjectNode analizzato con l’XML previsto, inclusi gli attributi e le dichiarazioni degli spazi dei nomi; il lavoro è completato quando la conversione preserva tali attributi e spazi dei nomi invece di emettere elementi figli.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
java
Ambito
backend
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.