简体   繁体   English

在Java / Groovy中将XML转换为Object []

[英]Converting XML to Object[] in Java/Groovy

I have XML which is something like this: 我有这样的XML:

<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. 然后,我采用obj并对其进行迭代,但似乎所有内容都是String,并且我希望“ no”为int。

My question is, is there any way, that by using Jackson Mapper classes to get ints? 我的问题是,通过使用Jackson Mapper类获取整数,有什么办法吗? 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. 我认为,如果我先使用标准json库将该XML转换为JSON,然后再使用JSON转换为Object,则它将包含整数。 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... 杰克逊应该做同样的事情,先转换为json,但是xmlmapper的行为似乎有所不同,所以我不确定在这里我真的缺少什么...

You can use a class to map to, where the desired field is of the desired type. 您可以使用类来映射到所需字段为所需类型的位置。 Eg (see XXX ) 例如(请参阅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)])'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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