pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.peng</groupId>
<artifactId>JSONTEST</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>JSONTEST Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!--JSONObject and JSONArray-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<!--文件流操作-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<!--Gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<finalName>JSONTEST</finalName>
</build>
</project>
JSONObject和JSONArray
生成Json格式数据
JsonObjectSample.java
package json;
import bean.Person;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
1、使用JSONObject对象put方法来构建;
2、使用HashMap及其子类如treeMap的put方法来构建;
3、使用JavaBean来构建JSONObject对象。
* Created by Peng
* Time: 2017/3/29 11:32
*/
public class JsonObjectSample {
public static void main(String[] args){
//JSONObjectTest();
//createByHashMap();
createByJavabean();
}
/*{
"name":"王小二",
"age":25,
"birthday":"1990-01-01",
"school":"蓝翔",
"major":["理发","挖掘机"],
"has_girlfriend":false,
"car":null,
"house":null
}*/
//通过JSONObject生成json
public static void JSONObjectTest(){
Object nullobj= null;
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","王小二");
jsonObject.put("age",25.2);
jsonObject.put("birthday","1990-01-01");
jsonObject.put("school","蓝翔");
jsonObject.put("major",new String[]{"理发","挖掘机"});
jsonObject.put("has_girlfriend",false);
jsonObject.put("car",nullobj);
jsonObject.put("house",nullobj);
jsonObject.put("comment","这是一个注释");
System.out.println(jsonObject.toString());
}
//通过Hashmap生成json
public static void createByHashMap(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","王小二");
map.put("age",25.2);
map.put("birthday","1990-01-01");
map.put("school","蓝翔");
map.put("major",new String[]{"理发","挖掘机"});
map.put("has_girlfriend",false);
map.put("car",null);
map.put("house",null);
map.put("comment","这是一个注释");
System.out.println(new JSONObject(map).toString());
}
//通过JavaBean生成json
public static void createByJavabean(){
Person person = new Person();
person.setName("王小二");
person.setAge(25);
person.setBirthay("1990-01-01");
person.setSchool("蓝翔");
person.setMajor(new String[]{"理发","挖掘机"});
person.setHas_girlfriend(false);
person.setCar(null);
person.setHouse(null);
person.setComment("这是一个注释");
System.out.println(new JSONObject(person));
}
}
Person.java
package bean;
import java.util.Arrays;
/**
* Created by Peng
* Time: 2017/3/29 11:50
*/
public class Person {
private String name;
private String school;
private boolean has_girlfriend;
private double age;
private Object car;
private String[] major;
private Object house;
private String comment;
private String birthay;
//getter and setter toString
}
读取Json格式数据
Test.json
{
"name":"王小二",
"age":25,
"birthday":"1990-01-01",
"school":"蓝翔",
"major":["理发","挖掘机"],
"has_girlfriend":false,
"car":null,
"house":null
}
ReadJsonSample.java
package json;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
/**
* Created by Peng
* Time: 2017/3/29 12:01
*/
public class ReadJsonSample {
public static void main(String[] args) throws IOException {
File file = new
File(ReadJsonSample.class.getResource("/Test.json").getFile());
String content = FileUtils.readFileToString(file,"utf-8");
JSONObject jsonObject = new JSONObject(content);
if(!jsonObject.isNull("name")){//可以先行判断是否为空
System.out.println("姓名:"+jsonObject.getString("name"));
}
System.out.println("年龄:"+jsonObject.getDouble("age"));
System.out.println("有没有女朋友:"+jsonObject.getBoolean("has_girlfriend"));
System.out.println("有没有车:"+jsonObject.get("car"));
JSONArray jsonArray = jsonObject.getJSONArray("major");
for(Object str:jsonArray){
System.out.print(str+" ");
}
}
}
使用Gson
生成Json
person.java
package bean;
import com.google.gson.annotations.SerializedName;
import java.util.Arrays;
/**
* Created by Peng
* Time: 2017/3/29
*/
public class Person {
@SerializedName("NAME")//创建json时,可以重命名
private String name;
private String school;
private boolean has_girlfriend;
private double age;
private Object car;
private String[] major;
private Object house;
private String comment;
private String birthay;
private transient String ignore;//这个属性不生成json
// setter getter and toString
}
GsonCreateSample.java
package gson;
import bean.Person;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Field;
/**
* Created by Peng
* Time: 2017/3/29 12:30
*/
public class GsonCreateSample {
public static void main(String[] args){
Person person = new Person();
person.setName("王小二");
person.setAge(25);
person.setBirthay("1990-01-01");
person.setSchool("蓝翔");
person.setMajor(new String[]{"理发","挖掘机"});
person.setHas_girlfriend(false);
person.setCar(null);
person.setHouse(null);
person.setComment("这是一个注释");
person.setIgnore("不要看见我");
GsonBuilder gsonBuilder = new GsonBuilder();
//格式化输出
gsonBuilder.setPrettyPrinting();
//自定义生成json
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
public String translateName(Field field) {
if(field.getName().equals("age")){
return "AGE";
}
return field.getName();
}
});
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(person));
}
/*{
"NAME": "王小二",
"school": "蓝翔",
"has_girlfriend": false,
"AGE": 25.0,
"major": [
"理发",
"挖掘机"
],
"comment": "这是一个注释",
"birthay": "1990-01-01"
}
Process finished with exit code 0
*/
}
Gson读取json格式文件
Test2.json
{
"birthday":"1990-01-01"
}
DateBean.java
package bean;
import java.util.Date;
/**
* 测试gson转换date类型的数据
* Created by Peng
* Time: 2017/3/29 13:10
*/
public class DateBean {
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "DateBean{" +
"birthday=" + birthday +
'}';
}
}
ListBean.java
package bean;
import java.util.List;
/**
* 测试Gson读取json文件,类型转换的问题
* Created by Peng
* Time: 2017/3/29 13:59
*/
public class ListBean {
//set也是类似
private List<String> major;
public List<String> getMajor() {
return major;
}
public void setMajor(List<String> major) {
this.major = major;
}
@Override
public String toString() {
return "ListBean{" +
"major=" + major +
'}';
}
}
Test3.json
{
"major":["理发","挖掘机"]
}
ReadJsonByGson.java
package gson;
import bean.DateBean;
import bean.ListBean;
import bean.Person;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import json.ReadJsonSample;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
/**
* Created by Peng
* Time: 2017/3/29 12:44
*/
public class ReadJsonByGson {
public static void main(String[] args) throws IOException {
test3();
}
public static void test1() throws IOException {
File file = new
File(ReadJsonSample.class.getResource("/Test.json").getFile());
String content = FileUtils.readFileToString(file,"utf-8");
Gson gson = new Gson();
Person person = gson.fromJson(content,Person.class);
System.out.println(person);
}
//测试把Date类型的数据读取
public static void test2() throws IOException {
File file = new
File(ReadJsonSample.class.getResource("/Test2.json").getFile());
String content = FileUtils.readFileToString(file,"utf-8");
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
DateBean dateBean = gson.fromJson(content,DateBean.class);
DateFormat formatter = DateFormat.getDateTimeInstance();
System.out.println(formatter.format(dateBean.getBirthday()));
/*System.out.println(dateBean.getBirthday().toLocaleString());*/
}
public static void test3() throws IOException {
File file = new
File(ReadJsonSample.class.getResource("/Test3.json").getFile());
String content = FileUtils.readFileToString(file,"utf-8");
Gson gson = new Gson();
ListBean listBean = gson.fromJson(content,ListBean.class);
System.out.println(listBean.getMajor());
System.out.println(listBean.getMajor().getClass());
/*[理发, 挖掘机]
class java.util.ArrayList*/
}
}