简体   繁体   中英

Converting XML to Object[] in Java/Groovy

I have XML which is something like this:

<jobs>
  <no>2</no>
  <job>
    <status>Completed</status>
  </job>
  <job>
    <status>In Progress</status>
  </job>
</jobs>

I tried this:

def xmlmapper = new XmlMapper()
def obj = xmlmapper.readValue(xml, Object[].class)

Then I take the obj and iterate thru it, but it seems that everything is String and I'd expect "no" to be int.

My question is, is there any way, that by using Jackson Mapper classes to get ints? I think, that if I'd convert that XML to JSON first using standard json library, and then JSON to Object, that would contain ints. Jackson was supposed to do the same, convert to json first, however the xmlmapper seems to behave differently, so I am not sure what I am really missing here...

You can use a class to map to, where the desired field is of the desired type. Eg (see XXX )

@Grab('com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.5.1')
import groovy.transform.ToString
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.dataformat.xml.annotation.*

@ToString
class Jobs {
    Integer no // XXX
    @ToString
    static class Job {
        String status
    }
    @JacksonXmlElementWrapper(useWrapping=false)
    List<Job> job
}

def xml="""<jobs><no>2</no><job><status>Completed</status></job><job><status>In Progress</status></job></jobs>"""

def xmlmapper = new XmlMapper()
def jobs = xmlmapper.readValue(xml, Jobs)
assert jobs.no==2
assert jobs.job.size()==jobs.no
assert jobs.toString()=='Jobs(2, [Jobs$Job(Completed), Jobs$Job(In Progress)])'

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