JSON - JavaScript Object Notation
什么是 JSON
JSON 是一种与开发语言无关的、轻量级的数据格式。
优点
易于人的阅读和编写,易于程序解析与生产。
JSON 的样例
{
"name" : "JSON快速入门",
"author" : "xq",
"content" : ["JSON 基础入门","常用的 JSON 处理"],
"time" : {
"value" : "30"
"unit" : "min"
}
}
JSON 数据表示
- 数据结构
- Object
- 使用花括号{}包含的键值对结构,Key 必须是 string 类型,value 为任何基本类型或数据结构。
- Array
- 使用中括号[]来起始,并用逗号,来分隔元素。
- Object
- 基本类型
- string
- number
- true
- false
- null
JSON 的生成
Maven 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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xq</groupId>
<artifactId>json</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
</project>
JsonObjectSample 类设计
package json;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import bean.Student;
public class JsonObjectSample {
public static void main(String[] args) {
jSONObjectSample();
//creatJsonByMap();
//creatJsonByBean();
}
/**
* { "name" : "xq", "age" : 25.2, "birthday" : "1998-09-17" }
*/
//生成
private static void jSONObjectSample() {
JSONObject wxe = new JSONObject();
Object nullObj = null;
try {
wxe.put("name", "wangxiaoer");
wxe.put("age", 25.2);
wxe.put("birthday", "1990-11-11");
wxe.put("school", "beida");
wxe.put("major", new String[] { "理发", "挖掘机" });
wxe.put("has_girlfrieng", false);
wxe.put("car", nullObj);
wxe.put("house", nullObj);
wxe.put("comment", "这是一个注释");
// print
System.out.println(wxe.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private static void creatJsonByMap() {
Map<String, Object> wxe = new HashMap<String, Object>();
Object nullObj = null;
wxe.put("name", "wangxiaoer");
wxe.put("age", 25.2);
wxe.put("birthday", "1990-11-11");
wxe.put("school", "beida");
wxe.put("major", new String[] { "理发", "挖掘机" });
wxe.put("has_girlfrieng", false);
wxe.put("car", nullObj);
wxe.put("house", nullObj);
wxe.put("comment", "这是一个注释");
System.out.println(new JSONObject(wxe).toString());
}
/**
* 推荐使用
*/
private static void creatJsonByBean() {
Student student = new Student();
student.setName("王小二");
student.setAge(25.2);
student.setBirthday("1999-11-11");
student.setSchool("lanxiang");
student.setHas_girlfriend(false);
student.setCar(null);
student.setHouse(null);
student.setComment("这是一个注释");
System.out.println(new JSONObject(student));
}
}
通过文件读取 JSON
package json;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 通过文件读取 JSON
* @author lenovo
*
*/
public class ReadJsonSample {
public static void main(String[] args) throws IOException, JSONException {
File file = new File(ReadJsonSample.class.getResource("/wxe.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = new JSONObject(content);
if(!jsonObject.isNull("name")) {
System.out.println("姓名是:" + jsonObject.getString("name"));
}
if(!jsonObject.isNull("nickname")) {
System.out.println("姓名是:" + jsonObject.getString("nickname"));
}
System.out.println("年龄是:" + jsonObject.getDouble("age"));
System.out.println(jsonObject.getBoolean("has_girlfriend"));
//获取数组对象
JSONArray majorArray = jsonObject.getJSONArray("major");
for (int i = 0; i < majorArray.length(); i++) {
String m = (String) majorArray.get(i);
System.out.println("专业-" + (i + 1) + m);
}
}
}
GSON
GsonCreateSample 类设计
package gson;
import java.lang.reflect.Field;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import bean.Student;
public class GsonCreatSample {
public static void main(String[] args) {
Student student = new Student();
student.setName("王小二");
student.setAge(25.2);
student.setBirthday("1999-11-11");
student.setSchool("lanxiang");
student.setMajor(new String[] {"蓝翔","挖掘机"});
student.setHas_girlfriend(false);
student.setCar(null);
student.setHouse(null);
student.setComment("这是一个注释");
student.setIgnore("不要看见我");
//
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
public String translateName(Field f) {
if(f.getName().equals("name")) {
return "NAME";
}
return f.getName();
}
});
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(student));
}
}
GsonReadSample 类设计
package gson;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import bean.Student;
import bean.StudentWithBirthday;
import json.ReadJsonSample;
public class GsonReadSample {
public static void main(String[] args) throws IOException {
File file = new File(ReadJsonSample.class.getResource("/wxe.json").getFile());
String content = FileUtils.readFileToString(file);
//定制 Date 类
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
StudentWithBirthday student = gson.fromJson(content, StudentWithBirthday.class);
System.out.println(student.getBirthday().toLocaleString());
//
System.out.println(student.getMajor());
System.out.println(student.getMajor().getClass());
}
}