使うライブラリ
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.4'
xmlに対応したクラスの定義
@JacksonXmlRootElement(localName = "root")
public class Simple {
private Child child;
public Child getChild() {
return child;
}
public void setChild(final Child child) {
this.child = child;
}
@Override
public String toString() {
return "Simple{" +
"child=" + child +
'}';
}
}
public class Child {
@JacksonXmlText
private String text;
@JacksonXmlProperty(isAttribute = true)
private String attr;
@Override
public String toString() {
return "Child{" +
"text='" + text + '\'' +
", attr='" + attr + '\'' +
'}';
}
}
xml→Java
XmlMapperのreadValueを使うfinal String xml = "あたい ";
final XmlMapper xmlMapper = new XmlMapper();
final Simple simple = xmlMapper.readValue(xml, Simple.class);
System.out.println("simple = " + simple); // simple = Simple{child=Child{text='あたい', attr='hoge'}}
java→xml
final Simple input = new Simple();
final Child child = new Child();
child.text = "値";
child.attr = "属性";
input.child = child;
System.out.println(xmlMapper.writeValueAsString(input)); // 値
kotlin data classを使う
以下を追加する。compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.4'
KotlinModuleを有効化することでdata classを使えるようになる。
@JacksonXmlRootElement(localName = "r")
data class Hoge(val hoge:String)
val xmlMapper = XmlMapper()
xmlMapper.registerModule(KotlinModule())
println(xmlMapper.writeValueAsString(Hoge("fugafuga")))