我正在使用 Jackson 来处理我的 XML 数据,基于 这个 Baeldung 教程。
我有以下类来建模some XML:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class SimpleBean {
private int x = 1;
private int y = 2;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public SimpleBean fromString(String xml) throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
return xmlMapper.readValue(xml, SimpleBean.class);
}
}
我通过了以下测试:
@Test
void testFromString() throws Exception {
SimpleBean bean = new SimpleBean();
String xml = "<SimpleBean><x>11</x><y>22</y></SimpleBean>";
SimpleBean beanParsed = bean.fromString(xml);
Assertions.assertEquals(11, beanParsed.getX());
}
我想做的是这样的:
@Test
void testFromStringWanted() throws Exception {
SimpleBean bean = new SimpleBean();
String xml = "<SimpleBean><x>11</x><y>22</y></SimpleBean>";
bean.fromString(xml);
Assertions.assertEquals(11, bean.getX()); // FAILS
}
我想将字符串解析为我已有的实例
bean
。我不想创建第二个beanParsed
。
我尝试将我的
fromString
方法更改为:
public void fromString(String xml) throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.readValue(xml, this.getClass());
}
但这没有用。没有错误,只是没有产生预期的结果。
也尝试过这个,但是甚至无法编译!
public void fromString(String xml) throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
this = xmlMapper.readValue(xml, SimpleBean.class);
}
我该怎么做?
尝试:
public void fromString(String xml) throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
// Use readerForUpdating() to parse into the existing instance
xmlMapper.readerForUpdating(this).readValue(xml);
}
Jackson 提供了一种名为
readerForUpdating()
的方法,专门用于将数据解析为现有对象。
此方法创建一个读取器,用于更新现有对象而不是创建新对象。