Josn的配置和使用
- JSON的基本概念
1.JSON(JavaScript Object Natation) —-javascript的對象表現形式,但是目前已經發展成爲一種輕量級的數據交換格式
最大特點:完全獨立於語言的文本格式(跨平臺數據格式)不依賴於任何語言、有結構的、方便人和機器解析
使用場景:
1):不同語言之間的數據傳遞(Json的本質就是String,但是它是有格式的),後臺的list轉換爲json,前端纔可以解析
比如EasyUI(javascript )+SSH(java)之間的數據傳遞
2)前端的js和後臺的java數據傳遞
比如:java處理完數據以List /Map/Set的數據格式輸出,但是這些數據格式無法被js識別
SSH和easyUI/EXTJS/Ajax進行交互是通過json格式數據來進行的
SSH和Flex(Adobe Flash)也是通過json格式的數據
HTML5 WebSocket —>javascript 之間的數據也是json
JSON與XML、Properties的區別
1.json是輕量級的,而XML是重量級的(比如web.xml配置過濾器、監聽器以及各種web組件 其中重要信息數據還沒有描述數據的標籤多)xml的可讀性是建立的在大量標籤基礎之上的。
目前xml一般用於項目(框架)配置,而很少用來進行數據傳輸
2.json是有結構的,但是properties僅僅是key-value鍵值對,意味着json可以傳送一些豐富複雜的數據,可以傳送含有子對象的對象
- JSON語法介紹
官網:www.json.org
空對象:{ }
json對象的結構:
{ "key":"value","key":"value"}
json數組的表現結構:
value可以是多種類型
[{ "key":"value","key":"value"},{ "key":"value","key":"value"},"abc"]
數值型
-3、3.5 、3.5e+5、5e-7、2e2合法
- JSON語法測試
要將java對象轉換成json對象,必須依賴一些jar包
json-lib-2.4-jdk1.5.jar所需要的全部jar包(6個)
commons-beanutils-1.8.0.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
新建JUint Test Case ,類名自定義
package cn.jxy.json;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class JSONTest {
private static Grade grade;
private static Student student;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("----測試方法執行之前執行----");
student = new Student();
grade = new Grade();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("----測試方法執行之後執行----");
student = null;//目的:釋放資源
grade = null;
}
@Test
// 測試Java對象轉成Json的格式
public void test() {
grade.setId(1);
grade.setName("java net");
System.out.println(JSONSerializer.toJSON(grade));
}
@Test
// 測試數組的JSON表現形式
public void test2() {
grade.setId(1);
grade.setName("java");
Student student = new Student();
student.setName("小王");
student.setDate(new Date());
Student student2 = new Student();
student2.setName("小李");
student2.setDate(new Date());
List<Student> stuList = new ArrayList<Student>();
stuList.add(student);
stuList.add(student2);
grade.setStulist(stuList);
System.out.println(JSONSerializer.toJSON(grade));//日期會具體細分新的json
}
@Test // 測試static是不能轉化爲json屬性的
public void test3() {
student.setDate(new Date());
student.setName("admin");
student.setAge(18);
System.out.println(JSONSerializer.toJSON(student));
// 如果返回的是static,或者返回的類型不確定,那麼可以採用map或者自己構建json格式
JSONObject object = new JSONObject();
object.put("age", student.getAge());
object.put("date", student.getDate());
object.put("name", student.getName());
System.out.println(object.toString());
}
@Test // 解決自關聯的問題
public void test4() {
student.setDate(new Date());
student.setName("admin");
//student.setStudent(new Student());
// 通過配置jsonConfig來過濾相應的參數
JsonConfig config=new JsonConfig();
// 設置需要排除哪些字段, 例如排除密碼字段
config.setExcludes(new String[]{"date"});
// 設置如果有些字段是自關聯則過濾 STRICT: 缺省值,是否自關聯都要轉化
// LENIENT: 如果有自關聯對象,則值設置爲null
// NOPROP: 如果自關聯則忽略屬性
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
System.out.println(JSONObject.fromObject(student, config));
}
@Test // 通過自定義日期的處理類,來格式化日期數據
public void test5() {
student.setDate(new Date());
student.setName("admin");
JsonConfig config=new JsonConfig();
// 指定某個Json類型的處理方式
DataJsonValueProcessor dataValue=new DataJsonValueProcessor();
config.registerJsonValueProcessor(Date.class, dataValue);
System.out.println(JSONObject.fromObject(student, config));
}
@Test // 通過自定義日期的處理類,來格式化日期數據
public void test6() {
// JSONObject 可以自定義對象,JSONArray可以自定義數組
JSONObject obj=new JSONObject();
obj.put("id", 123);
obj.put("name","admin");
JSONObject obj2=new JSONObject();
obj2.put("id", 234);
obj2.put("name","xyz");
JSONArray array=new JSONArray();
array.add(obj);
array.add(obj2);
// 吧array對象在存儲到obj對象中
JSONObject temp=new JSONObject();
temp.put("array", array); // {array:[{id:123,name:'admin'},{.....}]}
System.out.println(JSONObject.fromObject(temp));
}
}
將一個java對象轉換爲 json
JSONSerializer.toJSON(grade);
如果有字符串中含有特殊符號\t
前端發現\t會自動解釋爲tab鍵
- *如何轉換爲static字段
如果Student類中有靜態屬性(即用static聲明的屬性)
// 默認static屬於類的,而非對象的.
private static Integer age;
public static Integer getAge() {
return age;
}
public static void setAge(Integer age) {
Student.age = age;
}
則在轉換成json時無法識別
@Test // 測試static是不能轉化爲json屬性的
public void test3() {
//student.setDate(new Date());
student.setName("admin");
student.setAge(18);
System.out.println(JSONSerializer.toJSON(student));
無法正常輸出age字段
解決方法:
1)此方案不是很好 在web開發中會有線程安全的問題
//去掉get和set的static修飾符
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
Student.age = age;
}
可以正常轉化爲json
2)或者可以採用map(先行構建map,再將map轉換爲json)或者自己構建json格式(JSONObject–實質是一個map)
// 如果返回的是static,或者返回的類型不確定,那麼可以採用map(先行構建map,再將map轉換爲json)或者自己構建json格式(JSONObject--實質是一個map)
JSONObject object = new JSONObject();
object.put("age", student.getAge());
object.put("date", student.getDate());
object.put("name", student.getName());
System.out.println(object.toString());
對於零散數據map格式的數據使用比較多,跟對象屬是否爲static沒有關係
- 自關聯解決方案
如果在Student類中還有一個屬性(是它自己的類對象)
private Student student = this;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@Test // 解決自關聯的問題
public void test4() {
student.setDate(new Date());
student.setName("admin");
System.out.println(JSONSerializer.toJSON(student));
}
此時執行會報錯 net.sf.JSONException:There is acycle in the hierarchy 循環錯誤
解決方案
@Test // 解決自關聯的問題
public void test4() {
student.setDate(new Date());
student.setName("admin");
//通過配置jsonConfig來過濾相應的參數
JsonConfig config=new JsonConfig();
// 設置需要排除哪些字段, 例如排除密碼字段
config.setExcludes(new String[]{"student","date"});
JSONObject.fromObject(student,config);
System.out.println(JSONObject.fromObject(student,config).toString());
}
或者可以排除date字段
由於上述參照的是自己
private Student student = this;
但有時候
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@Test // 解決自關聯的問題
public void test4() {
student.setDate(new Date());
student.setName("admin");
//student.setStudent(new Student());
// 通過配置jsonConfig來過濾相應的參數
JsonConfig config=new JsonConfig();
// 設置需要排除哪些字段, 例如排除密碼字段
config.setExcludes(new String[]{"date"});
// 設置如果有些字段是自關聯則過濾 STRICT: 缺省值,是否自關聯都要轉化
// LENIENT: 如果有自關聯對象(是不是this),則值設置爲null
// NOPROP: 如果自關聯則忽略屬性(是this的話不管,沒有設個屬性)
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
System.out.println(JSONObject.fromObject(student, config).toString());
}
- Date格式處理
一般通過json傳遞的date都是字符串,這樣就避免了這種轉換
new Date() 轉化爲json的時候會細分到時分秒
期望用年月日的形式來展示
@Test // 通過自定義日期的處理類,來格式化日期數據
public void test5() {
student.setDate(new Date());
student.setName("admin");
JsonConfig config=new JsonConfig();
// 指定某個Json類型的處理方式 不僅僅可以處理日期
DataJsonValueProcessor dataValue=new DataJsonValueProcessor();
config.registerJsonValueProcessor(Date.class, dataValue);
System.out.println(JSONObject.fromObject(student, config));
}
擴展類
public class DataJsonValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd HH:mm:ss";
private SimpleDateFormat sdf = new SimpleDateFormat(format);
@Override
//針對數組
public Object processArrayValue(Object arg0, JsonConfig arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
// 需要處理日期的相關格式
//針對於普通值 arg0:匹配字段date arg1:date字段的值 arg2:jsonconfig對象
public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
if (arg1 == null) {
return "";
} else if (arg1 instanceof Date) {
return sdf.format((Date) arg1);
}else{
return arg1.toString();
}
}
}
JSONArray的使用
JSONObject實際上是一個map,可以自定義對象,
而JSONArray可以自定義數組
可以把對象放到數組裏邊 也可以把數組放到對象裏邊@Test
public void test6() {
// JSONObject 可以自定義對象,JSONArray可以自定義數組
JSONObject obj=new JSONObject();
obj.put(“id”, 123);
obj.put(“name”,”admin”);
JSONObject obj2=new JSONObject();
obj2.put(“id”, 234);
obj2.put(“name”,”xyz”);
JSONArray array=new JSONArray();
array.add(obj);
array.add(obj2);
// 把array對象在存儲到obj對象中
JSONObject temp=new JSONObject();
temp.put(“array”, array); // {array:[{id:123,name:’admin’},{…..}]}
System.out.println(JSONObject.fromObject(temp));
}