简体   繁体   中英

A generic XML to JSON converter in Scala

I have a few xml config files like :

<ConfigParams name="ABC">
    <params>
        <param name="campaignId" type="SINGLE_VALUED" validation="required" label="Campaign ID" />
    </params>
</ConfigParams>

Until now I was manually converting every XML to it's JSON counterpart for some arbitrary config xml CM.xml by doing something like this :

(cmXML \\ "params").foreach(x => {
  for (filter <- x.child.filterNot(y => (y \\ "@name").text.equalsIgnoreCase(StringUtils.EMPTY))){
    val label:String =       (filter \\ "@label").text
    val ftype:String =   (filter \\ "@type").text
    val name:String =        (filter \\ "@name").text
    val render:String  =      (filter \\ "@render").text
    val validation:Array[String] =   Option((filter \\ "@validation").text).getOrElse("").split(',')
    val group:String =  (filter \\ "@group").text
    val enumVals =
      if(! (filter \\ "values").isEmpty)
        for (filtervalue <-  ( (filter \\ "values").iterator.next()  \\ "name") ) yield  (filtervalue ).text
      else
        null
    cmParams += Map("label" -> label, "type" -> ftype , "name" ->   name , "render" -> render , "validation" -> validation, "group" -> group,  "values" ->  enumVals )
  }
})

However now am looking for something more generic. Can you please point me to a scala library ( or java) which after following a standard XML format can easily convert the XML to JSON?

Thanks in advance!

I'm not aware of something implemented in Scala, but you can use Java libraries to convert xml to map(such as JAXB) and then convert map to json(such as jackson)

here is some example in java: xml-to-json JSON-java

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