JSON 學習筆記
阿新 • • 發佈:2018-12-19
JSON - JavaScript Object Notation
什麼是 JSON
JSON 是一種與開發語言無關的、輕量級的資料格式。
優點
易於人的閱讀和編寫,易於程式解析與生產。
JSON 的樣例
{
"name" : "JSON快速入門",
"author" : "xq",
"content" : ["JSON 基礎入門","常用的 JSON 處理"],
"time" : {
"value" : "30"
"unit" : "min"
}
}
JSON 資料表示
- 資料結構
- Object
- 使用花括號{}包含的鍵值對結構,Key 必須是 string 型別
- 使用花括號{}包含的鍵值對結構,Key 必須是 string 型別
- 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>
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" : "熊奇", "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());
}
}