解析 XML 时拦截 Xstream
假设我有一个像这样的简单 Java 类:
public class User {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
现在,假设我想解析以下 XML:
<user>
<firstName>Homer</firstName>
<lastName>Simpson</lastName>
</user>
我可以在 XStream 中毫无问题地执行此操作,如下所示:
User homer = (User) xstream.fromXML(xml);
好的,到目前为止一切都很好,但这是我的问题。
假设我想要解析以下 XML:
<user>
<fullName>Homer Simpson</fullName>
</user>
如何使用 XStream 将此 XML 转换为相同 User 对象?
我想要一种实现某种回调的方法,以便当 XStream 解析 fullName 字段时,我可以将字符串分成两部分,并手动设置用户对象上的名字和姓氏字段。这可能吗?
请注意,我不是问如何将字符串分成两部分(这是简单的部分),我想知道如何拦截 XML 解析,以便 XStream 不会尝试反射性地设置 User 对象上的 fullName 字段(这显然是不存在)。
我查看了 XStream 提供的转换器,但不知道如何将其用于此目的。
任何帮助将不胜感激。
Suppose I have a simple Java class like this:
public class User {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Now, suppose I want to parse the following XML:
<user>
<firstName>Homer</firstName>
<lastName>Simpson</lastName>
</user>
I can do this with no problems in XStream like so:
User homer = (User) xstream.fromXML(xml);
Ok, all good so far, but here's my problem.
Suppose I have the following XML that I want to parse:
<user>
<fullName>Homer Simpson</fullName>
</user>
How can I convert this XML into the same User object using XStream?
I'd like a way to implement some kind of callback so that when XStream parses the fullName field, I can split the string in two and manually set the first name and last name fields on the user object. Is this possible?
Note that I'm not asking how to split the string in two (that's the easy part), I want to know how to intercept the XML parsing so XStream doesn't try to reflectively set the fullName field on the User object (which obviously doesn't exist).
I looked at the converters that XStream provides but couldn't figure out how to use it for this purpose.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要一个自定义转换器:
参考:http://x-stream.github.io/converter -tutorial.html
You need a custom converter:
Reference: http://x-stream.github.io/converter-tutorial.html