jackson这个开源包其实是个好东西,是对json转换进行的好东西。今天看到一个例子,综合
使用了apache common的ioutil包,jackson结合的例子,是将一个文件读入的XML转换为hashmap,
例子如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class XML2JSONConvertor {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(new File(
“e:\\jagannathan\\personal\\java-projects\\secondtest.xml”));
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xml);
System.out.println(json.toString(2));
printJSON(json.toString(2));
}
public static void printJSON(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> jsonInMap = mapper.readValue(jsonString,
new TypeReference<Map<String, Object>>() {
});
List<String> keys = new ArrayList<String>(jsonInMap.keySet());
for (String key : keys) {
System.out.println(key + “: ” + jsonInMap.get(key));
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
比如一个XML为:
<?xml version=”1.0″ encoding=”UTF-8″?>
<company>
<name>Jags Inc</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形式的输出:
7 Feb, 2013 7:20:50 PM net.sf.json.xml.XMLSerializer getType
INFO: Using default type string
{
“name”: “Jags Inc”,
“employees”: [
{
"name": "Jagan",
"sex": "Male",
"dob": "24-jul"
},
{
"name": "Satya",
"sex": "Male",
"dob": "24-apr"
}
]
}
name: Jags Inc
employees: [{name=Jagan, sex=Male, dob=24-jul}, {name=Satya, sex=Male, dob=24-apr}]
可以看到,jackson其实还是比较快的,听说测评比json-lib快,可以一用