Search code examples
javajsonxmlscalajackson-databind

Right configuration to convert a small and a large number from XML to Json using com.fasterxml.jackson.dataformat.xml.XmlMapper class


How can I configure the com.fasterxml.jackson.dataformat.xml.XmlMapper class so that given an xml like:

<Person>
    <Age>33</Age>
    <GrantID>815721008160186381772405</GrantID>
</Person>

Can turn it into a json string like:

{
    "Person": {
     "Age": 33,
     "GrantID": "815721008160186381772405"
     }
}

See the detail that 33 can be converted into a number, but 815721008160186381772405 cannot and is converted into a string.

My sample program:

import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
import com.fasterxml.jackson.dataformat.xml.XmlMapper

object Xml2Json extends App {
  val xml: String = "<Person><Age>33</Age><GrantID>815721008160186381772405</GrantID></Person>"
  val xmlMapper: XmlMapper = new XmlMapper()
  val node: JsonNode = xmlMapper.readTree(xml) //.readTree(xml.getBytes())
  val jsonMapper: ObjectMapper = new ObjectMapper()
  val json: String = jsonMapper.writeValueAsString(node)

  println(json)
}

Output:

{"Age":"33","GrantID":"815721008160186381772405"}

Solution

  • It is possible if you use the ObjectWriter.withRootName method with the constructed ObjectWriter writer from your already existing ObjectMapper mapper present in your code, so giving the correct rootname (in your case the value Person):

    val node: JsonNode = xmlMapper.readTree(xml)
    val jsonMapper: ObjectMapper = new ObjectMapper()
    val json: String = jsonMapper.writer()
                                 .withRootName("Person")
                                 .writeValueAsString(node)
    //Output: {"Person":{"Age":"33","GrantID":"815721008160186381772405"}}
    println(json)