I have this code:
@ElementList(name="package", required=false, inline=true)
private Hashtable<String, PackageListItem> packages;
which gives me this error:
D/debug(22150): java.util.Hashtable cannot be cast to java.util.Collection
I tried to fix that using a getter:
@ElementList(name="package", required=false, inline=true)
private Collection<PackageListItem> getPackageXML() {
return packages.values();
}
but that gives me an error I don't quite understand:
D/debug(22307): Default constructor can not accept read only @org.simpleframework.xml.ElementList(data=false, empty=true, entry=, inline=true, name=package, required=false, type=void) on method 'packageXML' in class com.example.MyClass
I know I can use a ElementMap
, but that gives too much information in my XML.
How can I serialize the values of a Hashtable
in Simple 2.7.1?
Alternatively you can use HashMap instead of Hashtable. They are nearly the same, so there is a high chance that it will be suitable for you. Here are the differences: Differences between HashMap and Hashtable?
And here is an example of using maps with simpleXML: http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#map
Update:
Well, Hashtable implements the Map interface, so it should work with the @ElementMap annotation. (You use @ElementList right now.)
Try something like that:
private Hashtable<String, PackageListItem> packages;
@ElementList
private List<PackageListItem> list;
public PropertyMap() {
this.packages = new Hashtable<String, PackageListItem>();
}
@Validate
public void validate() {
List<String> keys = new ArrayList<String>();
for(PackageListItem entry : list) {
String key = entry.getKey();
if(keys.contains(key)) {
throw new PersistenceException("Duplicate key %s", key);
}
keys.put(key);
}
}
@Commit
public void build() {
for(PackageListItem entry : list) {
packages.put(entry.getKey(), entry);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.