使用了apache common的IoUtil包,jackson结合的例子,是将一个文件读入的XML转换为hashmap,
例子如下:
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.IOException;
- importjava.io.InputStream;
- importjava.util.ArrayList;
- importjava.util.List;
- importjava.util.Map;
- importnet.sf.json.JSON;
- importnet.sf.json.xml.XMLSerializer;
- importorg.apache.commons.io.IoUtils;
- importorg.codehaus.jackson.JsonGenerationException;
- importorg.codehaus.jackson.map.JsonMappingException;
- importorg.codehaus.jackson.map.ObjectMapper;
- importorg.codehaus.jackson.type.TypeReference;
- publicclassXML2JSONConvertor{
- staticvoidmain(String[]args)throwsException{
- InputStreamis=newFileInputStream(newFile(
- “e:\\jagannathan\\personal\\java-projects\\secondtest.xml”));
- Stringxml=IoUtils.toString(is);
- XMLSerializerxmlSerializer=newXMLSerializer();
- JSONjson=xmlSerializer.read(xml);
- System.out.println(json.toString(2));
- printJSON(json.toString( }
- voidprintJSON(StringjsonString){
- ObjectMappermapper=newObjectMapper();
- try{
- Map<String,Object>jsonInMap=mapper.readValue(jsonString,
- newTypeReference<Map<String,Object>>(){
- });
- List<String>keys=newArrayList<String>(jsonInMap.keySet());
- for(Stringkey:keys){
- System.out.println(key+“:”+jsonInMap.get(key));
- }
- }catch(JsonGenerationExceptione){
- e.printStackTrace();
- catch(JsonMappingExceptione){
- catch(IOExceptione){
- }
比如一个XML为:
copy