简体   繁体   中英

Jackson serialization - dynamically change element name

I have the following XML that I have to convert to JSON:

<acme>
    <acme_name>1</acme_name>
    <acme_type>2</acme_type>
    <desc>desc0</desc>
</acme>

I'd want the following JSON:

{
   "acme":{
      "name":"1",
      "type":"2",
      "desc":"desc0"
   }
}

So what I want is

  • if the element name contains an underscore then use the text as element name after the underscore
  • leave the other element name untouched

There are Java beans behind the XML with @XmlElement annotations.
I cannot use jackson annotations in the Java beans as the classes come from a 3rd party source.

I thought I can use the JsonSerializer like

class GeneralSerializer extends JsonSerializer {

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        ...
    }
}

but I have to specify what Java bean I want to serialize (see below) and I cannot use the same serializer for all the elements.

public class ItemSerializer extends JsonSerializer<Item>

The problem is that there are lots of different elements in the XML and specifying serializers them which do the same (ie searching for the underscore characters and just using the text after it) seems an overkill.

Can I specify a common serializer that can be applied to every elements?
Is there any other solution by any chance?

Thank you for the help!

----------------- UPDATE 1 -----------------

I'd like to emphasize that I don't have the XML text but I have the Java beans (annotated with @Xml...) that represent the XML.

----------------- UPDATE 2 -----------------

I don't insist on Jackson. If there is a solution in another JSON library (eg GSON) then please don't spare me!

some ideas:

  1. serialize your beans to xml, then apply xslt transformations to rename the tags/change the structure to be more closer to your desired json
  2. create pojo with jackson annotations and deserialize using jackson xml module
  3. serialize from pojo to json

or

  1. create pojo with jackson annotations according to your target json
  2. use a bean mapper like dozer to map bean to pojo
  3. serialize from pojo to json

http://dozer.sourceforge.net/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM