list转成json对象

需要的包:
1.commons-lang.jar

2.commons-beanutils.jar

3.commons-collections.jar

4.commons-logging.jar

5.ezmorph.jar

6.json-lib-2.2.2-jdk15.jar


测试的例子:
可以用这个方法JSONArray.fromObject(list).toString();

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;

import com.yan.entity.Student;

public class List2Json {

	public static void main(String[] args) {
		List<Object> list = new ArrayList<Object>();
		List<Map<String, Object>> sublist = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("abc", "123456");
		map.put("def", "hmm");
		map.put("defddf", "ftffff");
		list.add(map);
		
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("fff", "hhhh");
		map1.put("ggg", "jjj");
		map1.put("kk", "dffff");
		sublist.add(map1);
		
		Student st = new Student();
		st.setSid(1);
		st.setName("alec");
		st.setTeacher("scott");
		
		list.add(st);
		
		list.add(sublist);
		JSONArray json = new JSONArray();
		json.addAll(list);
		json.listIterator();
		if(json.isEmpty()){
			System.out.println("dfdfdf");
		}
		ListIterator  li = json.listIterator();
		while(li.hasNext()){
			System.out.println(li.next().toString());
		}
	}

}



上面用到的一个简单的entity
public class Student {
	
	public Integer sid;
	public String name;
	public String teacher;
	
	public Integer getSid() {
		return sid;
	}
	public void setSid(Integer sid) {
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTeacher() {
		return teacher;
	}
	public void setTeacher(String teacher) {
		this.teacher = teacher;
	}
}



附件中是整个小工程,下载下来后导入eclipse中就可以运行。里边有用到的各个包

你可能感兴趣的:(json)