1、需要的jar包json-lib.jar

 

此包还需要以下的依赖包,

 

commons-lang.jar

commons-beanutils .jar

commons-collections.jar

commons-logging.jar

ezmorph.jar

 

2、创建javabean文件,以下面的为例:

 

package com.gdhdcy.whp;

public class person_bean {
	public int id;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getMoblie() {
		return moblie;
	}
	public void setMoblie(String moblie) {
		this.moblie = moblie;
	}
	public String name;
	public String sex;
	public String moblie;
	
}

 

 

3、bean/LIst/map生成json的代码:

 

package com.gdhdcy.whp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class json_create {
	public static void main(String args[]){
		
		//javabean生成json
		person_bean pb=new person_bean();
		pb.setId(1);
		pb.setName(wang);
		pb.setSex(男);
		pb.setMoblie(1341234568);
		JSONObject jsonobject=JSONObject.fromObject(pb);
		System.out.println(jsonobject.toString());
		//结果
		//{id:1,moblie:1341234568,name:wang,sex:男}
		
		//List生成json
		person_bean pb1=new person_bean();
		pb1.setId(2);
		pb1.setName(wang1);
		pb1.setSex(女);
		pb1.setMoblie(13123323);
		
		person_bean pb2=new person_bean();
		pb2.setId(3);
		pb2.setName(wang3);
		pb2.setSex(女);
		pb2.setMoblie(13232343673);
		
		List


 

 


4、运行的结果:

{id:1,moblie:1341234568,name:wang,sex:男}
[{id:2,moblie:13123323,name:wang1,sex:女},{id:3,moblie:13232343673,name:wang3,sex:女}]
{3:zhi,2:tian,1:hai}