欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSON入门Java篇-5-用JavaBean来构建JSON

程序员文章站 2022-03-10 08:22:24
...

    前面我们介绍用JSONObject和HashMap来构造JSON数据,其实实际项目开发中,可能更多利用JavaBean来构造JSON。简单来说,JavaBean是可复用的平*立的软件组件,也就是说复用性很高。

1.打开eclipse,新建两个包

JSON入门Java篇-5-用JavaBean来构建JSON

 

2.JavaBean类内容如下

package bean;
 
/**
 * @author Administrator
 *
 */
 
public class DiaoSi {
	
	private String name;
	private String school;
	private boolean has_girlfriend;
	private double age;
	private Object car;
	private Object hourse;
	private String[] major;
	private String birthday;
	
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	public String getSchool() {
		return school;
	}
	public void setSchool(String school) {
		this.school = school;
	}
	public boolean isHas_girlfriend() {
		return has_girlfriend;
	}
	public void setHas_girlfriend(boolean has_girlfriend) {
		this.has_girlfriend = has_girlfriend;
	}
	public double getAge() {
		return age;
	}
	public void setAge(double age) {
		this.age = age;
	}
	public Object getCar() {
		return car;
	}
	public void setCar(Object car) {
		this.car = car;
	}
	public Object getHourse() {
		return hourse;
	}
	public void setHourse(Object hourse) {
		this.hourse = hourse;
	}
	public String[] getMajor() {
		return major;
	}
	public void setMajor(String[] major) {
		this.major = major;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	
 
}

        这里有一个快捷方式生成get和set方法,在新建好了全部private变量之后,点击Eclipse中的Source,点击点击Generate Getters and Setters,然后勾选全部,就快速帮你创建好了set和get方法,建议你添加一下方法备注,这里我没添加。

3.测试类的写法

package json;
 
import org.json.JSONObject;
 
import bean.DiaoSi;
 
public class Demo1 {
	public static void main(String[] args){
		createJsonByMap();
		
	}
	
	public static void createJsonByMap(){
		
		DiaoSi zhangsan = new DiaoSi();
		zhangsan.setAge(25.2);
		zhangsan.setBirthday("1991-08-23");
		zhangsan.setCar(null);
		zhangsan.setHas_girlfriend(false);
		zhangsan.setHourse(null);
		zhangsan.setMajor(new String[]{"理发师", "挖掘机"});
		zhangsan.setName("张三");
		zhangsan.setSchool("蓝翔技校");
		
                System.out.println(new JSONObject(zhangsan).toString());
		
	}
 
}
   输出结果和前面文章是一样,三种方法,对照起来,看起来都差不多,当然都使用了JSONObject对象或者JSONObject的构造函数,是,建议用JavaBean的方法来构造JSON,达到复用的目的。

转载于:https://blog.csdn.net/u011541946/article/details/78118472