java - simpleframework 转换元素
问题描述
我有下节课
@Root
@Convert(RecordConverter.class)
public class Record {
public static final String DATE = "Date";
public static final String ID = "Id";
public static final String NOMINAL = "Nominal";
public static final String VALUE = "Value";
@Attribute(name = DATE)
String date;
@Attribute(name = ID)
String id;
@Element(name = NOMINAL)
int nominal;
@Element(name = VALUE)
String value;
}
我想为我的“值”使用转换器,因为它像字符串,但我需要它作为 BigDecimal。但是@Converter 或'Converter' 不适用于@Element,仅适用于@Attributes。
记录 XML 示例
<Record Date="05.03.2020" Id="R01235">
<Nominal>1</Nominal>
<Value>66,0784</Value>
</Record>
RecordConverter 类是
public class RecordConverter implements Converter<Record> {
Record record;
public Record read(InputNode node) throws Exception {
record = new Record();
record.setDate(node.getAttribute(DATE).getValue());
record.setId(node.getAttribute(ID).getValue());
if (node.getAttribute(NOMINAL) != null) {
record.setNominal(Integer.parseInt(node.getAttribute(NOMINAL).getValue()));
} else {
record.setNominal(1);
}
if (node.getAttribute(VALUE) != null) {
record.setValue(node.getAttribute(VALUE).getValue());
} else {
record.setValue("qw");
}
return record;
}
public void write(OutputNode node, Record value) throws Exception {
throw new UnsupportedOperationException("Not ready converter yet");
}
}
但是,我不能在这里得到任何“名义”或“价值”。
我的问题是如何将我的值从 String 66,0784 转换为 BigDecimal 66.0784 ?
解决方案
虽然我自己从来没有使用过简单的 XML 序列化框架。InputNode
但是看它的API,你可以自己遍历Converter
使用InputNode#getNext()
or InputNode#getNext(String)
。
例如:
public Record read(InputNode node) throws Exception {
final Record record = new Record();
record.setDate(node.getAttribute(DATE).getValue());
record.setId(node.getAttribute(ID).getValue());
// Default values
record.setNominal(1);
record.setValue(BigDecimal.ONE);
for (InputNode next = node.getNext(); next != null; next = node.getNext()) {
switch (next.getName()) {
case NOMINAL:
record.setNominal(Integer.parseInt(next.getValue()));
break;
case VALUE:
record.setValue(new BigDecimal(next.getValue()));
break;
}
}
return record;
}
注意,默认值也可以直接在模型Record
类中设置,如下所示:
记录.java
...
@Element(name = NOMINAL)
int nominal = 1;
@Element(name = VALUE)
BigDecimal value = BigDecimal.ONE;
...
推荐阅读
- scala - kafka如何使用scala将参数传递给消费者
- google-apps-script - 谷歌表格脚本在行尾移动单元格
- jquery - jQuery (Ajax) 在 Codeiginiter 中不起作用
- c - 请查看并建议
- memory - 我如何知道正在使用哪种数据结构?
- arrays - Laravel - Eloquent - 从返回数组中获取特定值
- java - 如何使用 @type 注释从 Hibernate 自定义用户类型类中动态返回 SQL 数据类型
- ruby - 用ruby语言在字符串中查找数组的元素
- apache-spark - Spark - 结构化流式 Kafka(动态反序列化)
- javascript - 你可以用 XMLHttpRequest 做什么而不能用 Fetch API 做什么?