将一个lIst转换为json的示例
/**
* @param args
* @author julong 2015-5-16 上午11:27:49
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//第一种方式
try {
//读取单对象集合
List<String> list = new ArrayList<String>();
String str1 = "张三";
String str2 = "张三1";
String str3 = "张三2";
String str4 = "张三3";
list.add(0, str1);
list.add(1, str2);
list.add(2, str3);
list.add(3, str4);
//创建mapper对象
ObjectMapper objectMapper = new ObjectMapper();
//格式化集合为json
String json = objectMapper.writeValueAsString(list);
System.out.println("json对象为:"+json);
//将json转换为List对象
List list1 = objectMapper.readValue(json, List.class);
System.out.println("java对象为:"+list1);
for (int i = 0; i < list1.size(); i++) {
System.out.println(list1.get(i));
}
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json对象为:["张三","张三1","张三2","张三3"]
java对象为:[张三, 张三1, 张三2, 张三3]
张三 张三1 张三2 张三3
需要三个jar包
jackson-annotations-2.4.0.jar
jackson-databind-2.4.0.jar
jackson-core-2.4.0.jar