我正在尝试使用org.simpleframework.xml
。用于处理Android项目中的xml数据的类。我无法理解如何构建我的类“Point”构造函数以匹配xml定义:在运行时我得到此异常:
org.simpleframework.xml.core.PersistenceException: Constructor not matched for class koine.marcos.wifidemo.Point
我的xml数据是这样的:
文件points.xml:
<?xml version="1.0" encoding="utf-8"?>
<points>
<point id="La Gioconda">
<rssi ssid="beacon1" bssid="00:21:91:d1:36:62">-52</rssi>
<rssi ssid="beacon2" bssid="00:12:a9:03:23:32">-97</rssi>
</point>
<point id="La Pietà">
<rssi ssid="beacon1" bssid="00:21:91:d1:36:62">-68</rssi>
<rssi ssid="beacon2" bssid="00:12:a9:03:23:32">-83</rssi>
</point>
</points>
文件Rssi.java:
@Root
public class Rssi {
@Attribute(required=false)
protected String id;
@Element(required=false)
protected Integer value;
... getters and setters ...
}
文件point.java:
@Root
public class Point {
@Attribute
protected String id;
@ElementMap(entry="rssi", key="id", attribute=false,
inline=true, required=false)
private Map<String,Integer> rssiMap;
public Point(String id, Map<String,Integer>rssi) {
this.id = id;
...
}
...
}
文件点:java:
@Element
public class Points {
@ElementList(inline=true, required=true)
private List<Point> list;
... getters and setters ...
}
答案 0 :(得分:5)
好吧,因为我曾经是firm advocate of how awesome Simple XML really is我认为我会给你一个完整的答案来解答这个问题,所以在这里。完全正常工作的代码。
// You can make this non private and more complex at will.
public class Points {
@ElementList(entry = "point", inline = true) public ArrayList<Point> points;
}
public class Point {
private final String id;
private final HashMap<String, Integer> rssiMap;
public Point(@Attribute(name = "id") String id, @ElementMap(attribute = true, entry = "rssi", key = "ssid", valueType = Integer.class, inline = true) HashMap<String, Integer> rssiMap) {
this.id = id;
this.rssiMap = rssiMap;
}
@Attribute(name = "id")
public String getId() {
return id;
}
@ElementMap(attribute = true, entry = "rssi", key = "ssid", valueType = Integer.class, inline = true)
public HashMap<String, Integer> getRssi() {
return rssiMap;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Serializer serial = new Persister();
// Warning: You will need to make sure that this file exists or change it.
File file = new File("data/data.xml");
Points points = serial.read(Points.class, file);
for(Point point : points.points) {
System.out.println(point.getId());
for(Entry<String, Integer> entry : point.getRssi().entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
}
}
}
这就是它的全部内容。它应该很容易读入您的数据。如果您要试用该代码,那么您必须确保的唯一事情是Main函数正确设置您要读取的文件,或者您只是为读取函数提供正确的输入。
P.S。我在我的电脑上测试了这个,所以我知道它有效。欢呼声。