1、json的基本知识
JSON: JavaScript Object Notation(JavaScript 对象表示法)
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。
2.
无需解析器,JavaScript 程序能够使用内建的 eval() 函数,用 JSON 数据来生成原生的 JavaScript 对象。
3. 数据类型(6)种
数字 123
字符串 "firstName":"John"
数组 ["firstName":"John" , "lastName":"Doe" ]
对象 { "firstName":"John" , "lastName":"Doe" }
逻辑 true / false
null null
4、使用场景:
一般用于不同语言之间的数据传递
js + java != 后台查询的数据放到list中,在转换成json才能被前台的js解析。
下面的测试用例已经覆盖了常用的格式转换
package ray.json;
import java.util.Date;
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 TestJson {
public static Student student;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("--------Before-------");
student = new Student();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("--------After-------");
student = null;
}
//测试默认转换,用于处理比较简单的情况,例如知道对象的类型为student
//而很多情况是不知道对象的类型的,这就需要自定义json格式或者为map(见下面testCase)
@Test
public void test1(){
student.setId(1);
student.setName("雷子诺");
System.out.println(JSONSerializer.toJSON(student));
}
@Test//测试静态字段转换
public void test2(){
student.setId(1);
student.setName("雷子诺");
student.setAge(1);
//默认情况下静态字段是不会转换为json对象的,因为静态字段是属于类,而非对象
//解决方法:自定义json格式或者转换为map
JSONObject object = new JSONObject();
object.put("Myid", student.getId());
object.put("myName", student.getName());
object.put("myAge", student.getAge());
System.out.println(object);
}
@Test // 解决自关联的问题
public void test3() {
student.setDate(new Date());
student.setName("雷子诺");
student.setAge(1);
//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("雷子诺");
JsonConfig config=new JsonConfig();
// 指定某个Json类型的处理方式
DataJsonValueProcessor dataValue=new DataJsonValueProcessor();
config.registerJsonValueProcessor(Date.class, dataValue);
System.out.println(JSONObject.fromObject(student, config));
}
}
看下Student类:package ray.json;
import java.util.Date;
public class Student {
private int id;
private String name;
private static int age;
private Date date;
//自关联情况。
private Student student /*= this*/;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static int getAge() {
return age;
}
public static void setAge(int age) {
Student.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", date=" + date + "]";
}
}
输出结果自己跑下测试用例。
另外这里我写了下最基本的JsonArray的转换方法
package ray.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSon {
public static JSONObject object = new JSONObject();
public static void main(String[] args) {
testList();
testMap();
testBean();
testArray();
testCommon();
testObject();
}
//封装到JsonObject中,在需要的地方解析Json即可
private static void testObject() {
System.out.println(object);
}
//一般数据转换成json代码
private static void testCommon() {
JSONArray jsonAry = JSONArray.fromObject("['Uno','is', '梓诺的', 'father']" );
//["Uno","is","梓诺的","father"]
System.out.println(jsonAry);
object.put("jsonCommonAry", jsonAry);
}
//数组转换成json代码
private static void testArray() {
boolean[] ary = new boolean[] { true, false, true };
JSONArray jsonAry = JSONArray.fromObject(ary);
//[true,false,true]
System.out.println(jsonAry);
object.put("jsonAry", jsonAry);
}
//Bean转为Json,注意这个Bean一定要是public的class,否则抛异常
private static void testBean() {
Student student = new Student();
student.setId(1);
student.setName("雷梓诺");
JSONObject jsonObject = JSONObject.fromObject(student);
//{"id":1,"name":"雷梓诺"}
System.out.println(jsonObject);
object.put("Bean", jsonObject);
}
//Map集合转换成json方法
private static void testMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "雷梓诺");
map.put("bool", Boolean.TRUE);
map.put("int", null);
map.put("arr", new String[] { "a", "b" });
// map.put(null, null);//JSON keys cannot be null.
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
//{"arr":["a","b"],"int":null,"name":"雷梓诺","func":function(i){ return this.arr[i]; },"bool":true}
System.out.println(json);
object.put("jsonMap", json);
}
//List集合转换成json方法
private static void testList() {
List<String> list = new ArrayList<String>();
list.add( "first" );
list.add( "second" );
JSONArray ary = JSONArray.fromObject( list );
System.out.println(ary);//["first","second"]
object.put("list", ary);
}
}