jackson这个开源包其实是个好东西,是对json转换进行的好东西。今天看到一个例子,综合
使用了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:jagannathanpersonaljava-projectssecondtest.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
<?xmlversion=”1.0″encoding=”UTF-8″?>
- <company>
- <name>JagsInc</name>
- <employees>
- <employee>
- <name>Jagan</name>
- <sex>Male</sex>
- <dob>24-jul</dob>
- </employee>
- <employee>
- <name>Satya</name>
- <sex>Male</sex>
- <dob>24-apr</dob>
- </employee>
- </employees>
- </company>
则可以看到jackson输出的map形式的输出:
copy
7Feb,20137:20:50PMnet.sf.json.xml.XMLSerializergetType
- INFO:Usingdefaulttypestring
- {
- “name”:“JagsInc”,
- “employees”:[
- {
- "name":"Jagan",
- "sex":"Male",
- "dob":"24-jul"
- },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"
- ]
- name:JagsInc
- employees:[{name=Jagan,sex=Male,dob=24-jul},{name=Satya,dob=24-apr}]
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|