一.JSON基础
定义:JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
1.JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
2.JSON 是轻量级的文本数据交换格式
3.JSON 独立于语言 *
4.JSON 具有自我描述性,更易理解
5. JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。
语法
:在 JS 语言中,一切都是对象。因此,任何支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。但是对象和数组是比较特殊且常用的两种类型:
**1.对象表示为键值对
2.数据由逗号分隔
3.花括号保存对象
4.方括号保存数组**
1>.对象转为JSON字符串
public class JsonTest {
@Test
public void test1(){
try {
Address addr = new Address();
addr.setHomeAddr("西安");
addr.setBusiAddr("北京");
addr.setSchoolAddr("西安");
addr.setPhone("18039489556");
Student st = new Student();
st.setName("张三");
st.setId(1111);
st.setSex('男');
st.setAge(18);
st.setAddress(addr);
Address addr1 = new Address();
addr1.setHomeAddr("成都");
addr1.setBusiAddr("杭州");
addr1.setSchoolAddr("成都");
addr1.setPhone("13992526211");
Student st1 = new Student();
st1.setName("李四");
st1.setId(2222);
st1.setSex('男');
st1.setAge(19);
st1.setAddress(addr1);
//创建学生对象
Student[] students = new Student[]{st, st1};
//将对象通过映射转换为jsonvalue的json字符串
JSONValue jsonValue = JSONMapper.toJSON(students);
//将字符串排列
String jsonStr = jsonValue.render(true);
//控制台输出json字符串
System.out.println(jsonStr);
//不将字符串排列
String jsonStr1 = jsonValue.render(false);
System.out.println(jsonStr1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
控制台输出:
①jsonValue.render(true)—-字符串排列后:
[
{
"address" :
{
"busiAddr" : "北京",
"homeAddr" : "西安",
"phone" : "18039489556",
"schoolAddr" : "西安"
},
"age" : 18,
"id" : 1111,
"name" : "张三",
"sex" : "男"
},
{
"address" :
{
"busiAddr" : "杭州",
"homeAddr" : "成都",
"phone" : "13992526211",
"schoolAddr" : "成都"
},
"age" : 19,
"id" : 2222,
"name" : "李四",
"sex" : "男"
}
]
②jsonValue.render(false)—-json字符串未排列:
[{"address":{"busiAddr":"北京","homeAddr":"西安","phone":"18039489556","schoolAddr":"西安"},"age":18,"id":1111,"name":"张三","sex":"男"},{"address":{"busiAddr":"杭州","homeAddr":"成都","phone":"13992526211","schoolAddr":"成都"},"age":19,"id":2222,"name":"李四","sex":"男"}]
其中Student类,Address类
Student类:
public class Student {
private String name;
private int id;
private int age;
private char sex;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
Address类:
public class Address {
private String homeAddr;
private String busiAddr;
private String schoolAddr;
private String phone;
public String getHomeAddr() {
return homeAddr;
}
public void setHomeAddr(String homeAddr) {
this.homeAddr = homeAddr;
}
public String getBusiAddr() {
return busiAddr;
}
public void setBusiAddr(String busiAddr) {
this.busiAddr = busiAddr;
}
public String getSchoolAddr() {
return schoolAddr;
}
public void setSchoolAddr(String schoolAddr) {
this.schoolAddr = schoolAddr;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
在实际项目中:json字符串不排列将节省很多字符,可以增加有用数据的传输量
2>.将字符串转换为对象
注意:需要转json值的字符串中的双引号格式为: \”
string
\”
@Test
public void test2(){
try {
String jsonStr = "{\"address\":{\"busiAddr\":\"北京\",\"homeAddr\":\"西安\",\"name\":\"张三\",\"sex\":\"男\"}";
JSONValue jsonValue = new JSONParser(new StringReader(jsonStr)).nextValue();
Student s = (Student)JSONMapper.toJava(jsonValue, Student.class);
System.out.println("name" + ":" + s.getName());
System.out.println("id" + ":" + s.getId());
System.out.println("age" + ":" + s.getAge());
System.out.println("address" + ":" + s.getAddress());
System.out.println("sex" + ":" + s.getSex());
} catch (Exception e) {
e.printStackTrace();
}
}
控制台输出Student对象数据:
name:张三
id:1111
age:18
address:testUnit1.Address@69222c14
sex:男
二.JSON工具类
JSON工具类所需要的jar包
百度云
链接:
https://pan.baidu.com/s/1LtvktcPx6BlQp2IH0TVOpQ
密码:0ovu
工具类:
public class JSONUtil {
/**
* 将对象转为Json串
* @param o
* @return
*/
public static String toJson(Object o){
String str = null;
try {
str = JSONMapper.toJSON(o).render(false);
} catch (MapperException e) {
e.printStackTrace();
}
return str;
}
/**
* 将字符串转为Java对象
* @param jsonStr
* @return
*/
public static Object toJava(String jsonStr){
Object o = null;
try {
o = JSONMapper.toJava(new JSONParser(new StringReader(jsonStr)).nextValue(), GamePackage.class);
} catch (TokenStreamException e) {
e.printStackTrace();
} catch (RecognitionException e) {
e.printStackTrace();
} catch (MapperException e) {
e.printStackTrace();
}
return o;
}
}
用法:
1.将VO包转换为JSON串:
VO
(value object) 值对象 通常用于业务层之间的数据传递。
//GamePackage为VO包
GamePackage gp = new GamePackage();
//转为JSON串
String jsonString = JSONUtil.toJson(gp);
//发送数据包,9999为接收端口
DatagramPacket packet = new DatagramPacket(jsonString.getBytes(),jsonString.getBytes().length, InetAddress.getByName(ip), 9999);
ds.send(packet);
2.将json串转为VO对象包
//准备接收的数据包
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
try {
//接收数据包
ds.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
//得到字符串(数据, 开始字节, 数据长度)
String jsonStr = new String(packet.getData(),0, packet.getLength());
GamePackage pkg = (GamePackage)JSONUtil.toJava(jsonStr);