I need to convert this XML:
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Status>0</Status>
<Credit>98</Credit>
</Response>
to a Java HashMap using XStream:
XStream xStream = new XStream();
xStream.alias("hashmap", java.util.HashMap.class);
HashMap<String, Object> myHashmap = (HashMap<String, Object>) xStream.fromXML(myXmlAsString);
but this exception is thrown:
com.thoughtworks.xstream.mapper.CannotResolveClassException: Response
My question is: what am I doing wroing? I've browsed similar threads here but none seem to help. Any advice appreciated
I'm not sure this is the exact answer, but let's try.
IMO the error is trying to map an XML directly into an HashMap, without telling XStream how to do it.
For this reason I suggest to generate a Class which reflects xml schema and a second Class which maps the first one into a Map.
For example, I put your code in this simple class:
enter code herepackage com.stackoverflow.test.xstream_xml_to_map;
import java.io.File;
import com.thoughtworks.xstream.XStream;
public class App {
public static void main(String[] args) {
XStream xStream = new XStream();
File f = new File(App.class.getClassLoader().getResource("provided.xml").getFile());
xStream.alias("Response", Response.class);
Response res = (Response) xStream.fromXML(f);
System.out.println("Credit: "+res.getCredit());
System.out.println("Status: "+res.getStatus());
}
}
using this Response class:
package com.stackoverflow.test.xstream_xml_to_map;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Response")
public class Response {
private String Status = new String();
private String Credit = new String();
public String getStatus() {
return Status;
}
public String getCredit() {
return Credit;
}
}
Now you can use res object to generate the HashMap you prefer