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

使用Java构建json

程序员文章站 2024-01-30 16:44:10
...

注:这里要使用到json.jar包

具体的代码如下:

package testJson;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import bean.DiaoSi;

public class CreateJson {

	public static void main(String[] args) {
		createJsonByPut();
		createJsonByMap();
		createJsonByBean();
	}

	// 使用put方法构建
	private static void createJsonByPut() {
		JSONObject wangxiaoer = new JSONObject();
		String nullObj = null;
		try {
			wangxiaoer.put("name", "王小二");
			wangxiaoer.put("age", 25.2);
			wangxiaoer.put("birthday", "1990-01-01");
			wangxiaoer.put("school", "蓝翔");
			wangxiaoer.put("major", new String[] {"理发", "挖掘机"});
			wangxiaoer.put("house", nullObj); // 这里不能直接写null
			
			System.out.println(wangxiaoer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 使用map方式构建
	private static void createJsonByMap() {
		Map<String, Object> wangxiaoer = new HashMap<String, Object>();
		Object nullObj = null;
		
		wangxiaoer.put("name", "王小二");
		wangxiaoer.put("age", 25.2);
		wangxiaoer.put("birthday", "1990-01-01");
		wangxiaoer.put("school", "蓝翔");
		wangxiaoer.put("major", new String[] {"理发", "挖掘机"});
		wangxiaoer.put("house", nullObj);
		
		System.out.println(new JSONObject(wangxiaoer).toString());
	}
	
	// 使用Java Bean
	private static void createJsonByBean() {
		DiaoSi wangxiaoer = new DiaoSi();
		
		wangxiaoer.setName("王小二");
		wangxiaoer.setAge(25.2);
		wangxiaoer.setBirthday("1990-01-01");
		wangxiaoer.setSchool("蓝翔");
		wangxiaoer.setMajor(new String[] {"理发", "挖掘机"});
		wangxiaoer.setHouse(null);
		
		System.out.println(new JSONObject(wangxiaoer).toString());
	}
}

第三种方式中使用到的java bean代码如下:

package bean;

public class DiaoSi {
	
	private String name;
	private String school;
	private double age;
	private Object house;
	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 double getAge() {
		return age;
	}
	public void setAge(double age) {
		this.age = age;
	}
	public Object getHouse() {
		return house;
	}
	public void setHouse(Object house) {
		this.house = house;
	}
	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;
	}
	
}

最后我们看这三种方式所输出的结果:

{"birthday":"1990-01-01","school":"蓝翔","age":25.2,"name":"王小二","major":["理发","挖掘机"]}
{"birthday":"1990-01-01","school":"蓝翔","age":25.2,"name":"王小二","house":null,"major":["理发","挖掘机"]}
{"birthday":"1990-01-01","school":"蓝翔","age":25.2,"name":"王小二","house":null,"major":["理发","挖掘机"]}

可以看到,第一种put方法构建的json直接过滤掉了为null的house项

相关标签: json