使用jackson转换xml为hashmap形式

前端之家收集整理的这篇文章主要介绍了使用jackson转换xml为hashmap形式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
jackson这个开源包其实是个好东西,是对json转换进行的好东西。今天看到一个例子,综合
使用了apache common的IoUtil包,jackson结合的例子,是将一个文件读入的XML转换为hashmap,

例子如下:
[java] view plain copy
  1. importjava.io.File;
  2. importjava.io.FileInputStream;
  3. importjava.io.IOException;
  4. importjava.io.InputStream;
  5. importjava.util.ArrayList;
  6. importjava.util.List;
  7. importjava.util.Map;
  8. importnet.sf.json.JSON;
  9. importnet.sf.json.xml.XMLSerializer;
  10. importorg.apache.commons.io.IoUtils;
  11. importorg.codehaus.jackson.JsonGenerationException;
  12. importorg.codehaus.jackson.map.JsonMappingException;
  13. importorg.codehaus.jackson.map.ObjectMapper;
  14. importorg.codehaus.jackson.type.TypeReference;
  15. publicclassXML2JSONConvertor{
  16. staticvoidmain(String[]args)throwsException{
  17. InputStreamis=newFileInputStream(newFile(
  18. “e:\\jagannathan\\personal\\java-projects\\secondtest.xml”));
  19. Stringxml=IoUtils.toString(is);
  20. XMLSerializerxmlSerializer=newXMLSerializer();
  21. JSONjson=xmlSerializer.read(xml);
  22. System.out.println(json.toString(2));
  23. printJSON(json.toString( }
  24. voidprintJSON(StringjsonString){
  25. ObjectMappermapper=newObjectMapper();
  26. try{
  27. Map<String,Object>jsonInMap=mapper.readValue(jsonString,
  28. newTypeReference<Map<String,Object>>(){
  29. });
  30. List<String>keys=newArrayList<String>(jsonInMap.keySet());
  31. for(Stringkey:keys){
  32. System.out.println(key+“:”+jsonInMap.get(key));
  33. }
  34. }catch(JsonGenerationExceptione){
  35. e.printStackTrace();
  36. catch(JsonMappingExceptione){
  37. catch(IOExceptione){
  38. }

比如一个XML为:
copy
    <?xmlversion=”1.0″encoding=”UTF-8″?>
  1. <company>
  2. <name>JagsInc</name>
  3. <employees>
  4. <employee>
  5. <name>Jagan</name>
  6. <sex>Male</sex>
  7. <dob>24-jul</dob>
  8. </employee>
  9. <employee>
  10. <name>Satya</name>
  11. <sex>Male</sex>
  12. <dob>24-apr</dob>
  13. </employee>
  14. </employees>
  15. </company>

则可以看到jackson输出的map形式的输出
copy
    7Feb,20137:20:50PMnet.sf.json.xml.XMLSerializergetType
  1. INFO:Usingdefaulttypestring
  2. {
  3. “name”:“JagsInc”,
  4. “employees”:[
  5. {
  6. "name":"Jagan",
  7. "sex":"Male",
  8. "dob":"24-jul"
  9. },248)"> "name":"Satya",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "sex":"Male",248)"> "dob":"24-apr"
  10. ]
  11. name:JagsInc
  12. employees:[{name=Jagan,sex=Male,dob=24-jul},{name=Satya,dob=24-apr}]

猜你在找的XML相关文章