List转换成JSON对象
1、准备工作
导入jar包
(1)json-lib-2.3-jdk15.jar
(2)commons-beanutils-1.8.0.jar
(3)commons-collections-3.1.jar
(4)commons-lang-2.4.jar
(5)commons-logging-1.1.3.jar
(6)ezmorph-1.0.6.jar
2、设计源码
/**
* @Title:ListToJSON.java
* @Package:com.you.file.upload.util
* @Description:List转换为JSON对象
* @author:Youhaidong(游海东)
* @date:2014-5-2 下午10:57:10
* @version V1.0
*/
package com.you.file.upload.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import net.sf.json.JSONArray;
/**
* 类功能说明
* 类修改者 修改日期
* 修改说明
* <p>Title:ListToJSON.java</p>
* <p>Description:游海东个人开发</p>
* <p>Copyright:Copyright(c)2013</p>
* @author:游海东
* @date:2014-5-2 下午10:57:10
* @version V1.0
*/
public class ListToJSON
{
/**
* @Title:main
* @Description:
* @param:@param args
* @return: void
* @throws
*/
@SuppressWarnings("rawtypes")
public static void main(String[] args)
{
/**
* list对象
*/
List<Object> list = new ArrayList<Object>();
/**
* childList对象
*/
List<Map<String,Object>> childList = new ArrayList<Map<String,Object>>();
/**
* map对象
*/
Map<String, Object> map = new HashMap<String, Object>();
/**
* 添加键值对
*/
map.put("name", "张三");
map.put("age", "22");
map.put("sex", "男");
list.add(map);
/**
* 添加键值对
*/
Map<String, Object> childMap = new HashMap<String, Object>();
childMap.put("name", "李四");
childMap.put("age", "20");
childMap.put("sex", "女");
childList.add(childMap);
/**
* 将childList添加到list中
*/
list.add(childList);
/**
* 声明json数组
*/
JSONArray json = new JSONArray();
/**
* 将list转换成JSON
*/
json.addAll(list);
/**
* 打印转换结果
*/
System.out.println(json.toString());
json.listIterator();
if(json.isEmpty())
{
System.out.println(json);
}
ListIterator li = json.listIterator();
while(li.hasNext())
{
System.out.println(li.next().toString());
}
}
}
3、设计结果
[{"sex":"男","age":"22","name":"张三"},[{"sex":"女","age":"20","name":"李四"}]]
{"sex":"男","age":"22","name":"张三"}
[{"sex":"女","age":"20","name":"李四"}]