JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于javascript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
Fastjson是国内著名的电子商务互联网公司阿里巴巴内部开发的用于java后台处理json格式数据的一个工具包,包括“序列化”和“反序列化”两部分,它具备如下特征
a)速度最快,测试表明,fastjson具有极快的性能,超越任其他的java json parser。包括自称最快的jackson
b)功能强大,完全支持java bean、集合、Map、日期、Enum,支持范型,支持自省
c)无依赖,能够直接运行在Java SE 5.0以上版本
d)支持Android
e)这是fastJson的网址:http://code.alibabatech.com/wiki/display/FastJSON/Overview其中包含了json数据处理的教程,jar下载地址,example样例等
● JSONObject
json对象,就是一个键对应一个值,使用的是大括号{ },如:{key:value}
● JSONArray
json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的
注意:Json对象中是添加的键值对,JSONArray中添加的是Json对象
简单示例:
public class JsonTest {
public static void main(String[] args) {
// Json对象中是添加的键值对,JSONArray中添加的是Json对象
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject1.put("001","jack");
// JSONObject 对象中添加键值对
jsonObject.put("key","values");
// 将JSONObject对象添加到json数组中
jsonArray.add(jsonObject);
jsonArray.add(jsonObject1);
System.out.println(jsonArray.toString());
// 输出结果: [{"key":"values"},{"001":"jack"}]
}
}
官方示例:
package com.orange.com.orange.json.fastjson;
import java.util.List;
public class Group {
private int id;
private String name;
List<User> users;
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 List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
class User{
private int id;
private String name;
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;
}
}
package com.orange.com.orange.json.fastjson;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class FastJsonTest {
public static void main(String[] args) {
Group group = new Group();
group.setId(0);
group.setName("admin");
User user = new User();
user.setId(001);
user.setName("guest");
User user1 = new User();
user1.setId(002);
user1.setName("root");
List<User> users = new ArrayList<User>();
users.add(user);
users.add(user1);
group.setUsers(users);
String json = JSON.toJSONString(group);
System.out.println(json);
// 输出: {"id":0,"name":"admin","users":[{"id":1,"name":"guest"},{"id":2,"name":"root"}]}
}
}
package test.com.orange.com.orange.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.orange.com.orange.json.fastjson.People;
import org.junit.Test;
import static org.junit.Assert.*;
public class FastJsonTestTest {
/**
* 序列化
*/
@Test
public void toJsonString() {
People people = new People("001","tom",12);
String text = JSON.toJSONString(people);
System.out.println(text);
// 输出结果: {"age":12,"id":"001","name":"tom"}
}
/**
* 反序列为Json对象
*/
@Test
public void parseJsonObject(){
String text = "{\"age\":12,\"id\":\"001\",\"name\":\"tom\"}";
People people = (People) JSON.parseObject(text,People.class);
System.out.println("parseBeanObject()方法:people==" + people.getId() + "," + people.getName() + "," + people.getAge());
// 输出结果为: parseBeanObject()方法:people==001,tom,12
}
/**
* 将javaBean转化为json对象
*/
@Test
public void bean2Json(){
People people = new People("002","jack",23);
JSONObject jsonObject = (JSONObject) JSON.toJSON(people);
System.out.println("bean2Json()方法:jsonObject==" + jsonObject);
// 输出结果: bean2Json()方法:jsonObject=={"name":"jack","id":"002","age":23}
}
/**
* 全序列化 直接把java bean序列化为json文本之后,能够按照原来的类型反序列化回来。支持全序列化,需要打开SerializerFeature.WriteClassName特性
*/
@Test
public void parseJSONAndBeanEachother(){
People people = new People("002","jack",23);
SerializerFeature[] featureArr = { SerializerFeature.WriteClassName };
String text = JSON.toJSONString(people, featureArr);
System.out.println("parseJSONAndBeanEachother()方法:text==" + text);
// 输出结果:parseJSONAndBeanEachother()方法:text=={"@type":"com.wanggs.com.wanggs.json.fastjson.People","age":23,"id":"002","name":"jack"}
People people1 = (People) JSON.parse(text);
System.out.println("parseJSONAndBeanEachother()方法:People==" + people1.getId() + "," + people1.getName() + "," + people1.getAge());
// 输出结果:userObj==testFastJson001,maks,105
}
}
javaBean类People.java:
package com.orange.com.orange.json.fastjson;
public class People {
private String id;
private String name;
private int age;
public People() {
}
public People(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package test.com.orange.com.orange.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.orange.com.orange.json.fastjson.Address;
import com.orange.com.orange.json.fastjson.People;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class FastJsonTest1Test {
/**
* 数组转json字符串
*/
@Test
public void array2Json() {
String[] arr = {"bill", "green", "maks", "jim"};
String jsonText = JSON.toJSONString(arr);
System.out.println("array2Json()方法:jsonText==" + jsonText);
// 输出结果:jsonText==["bill","green","maks","jim"]
}
/**
* json格式字符串转数组
*/
@Test
public void json2Array() {
String jsonText = "[\"bill\",\"green\",\"maks\",\"jim\"]";
JSONArray jsonArray = JSON.parseArray(jsonText);
System.out.println("json2Array()方法:jsonArray==" + jsonArray);
// 输出结果:jsonArray==["bill","green","maks","jim"]
}
/**
* 数组转json格式字符串
*/
@Test
public void array2Json2() {
People people = new People("001", "tom", 12);
People people1 = new People("002", "jack", 23);
People people2 = new People("003", "mair", 22);
People[] peoples = new People[]{people, people1, people2};
String jsonText = JSON.toJSONString(peoples);
System.out.println("array2Json2()方法:jsonText==" + jsonText);
//输出结果:array2Json2()方法:jsonText==[{"age":12,"id":"001","name":"tom"},{"age":23,"id":"002","name":"jack"},{"age":22,"id":"003","name":"mair"}]
}
/**
* json格式字符串转数组
*/
@Test
public void json2Array2() {
String jsonText = "[{\"age\":12,\"id\":\"001\",\"name\":\"tom\"},{\"age\":23,\"id\":\"002\",\"name\":\"jack\"},{\"age\":22,\"id\":\"003\",\"name\":\"mair\"}]";
JSONArray jsonArr = JSON.parseArray(jsonText);
System.out.println("json2Array2()方法:jsonArr==" + jsonArr);
// 输出结果:json2Array2()方法:jsonArr==[{"name":"tom","id":"001","age":12},{"name":"jack","id":"002","age":23},{"name":"mair","id":"003","age":22}]
}
/**
* list集合转json格式字符串
*/
@Test
public void list2Json() {
List<People> list = new ArrayList<People>();
list.add(new People("001", "tom", 12));
list.add(new People("002", "jack", 23));
list.add(new People("003", "mair", 22));
String jsonText = JSON.toJSONString(list);
System.out.println("list2Json()方法:jsonText==" + jsonText);
// 输出的结果为: [{"age":12,"id":"001","name":"tom"},{"age":23,"id":"002","name":"jack"},{"age":22,"id":"003","name":"mair"}]
}
/**
* map转json格式字符串
*/
@Test
public void map2Json() {
Map map = new HashMap();
Address address1 = new Address("广东省","深圳市","科苑南路","580053");
map.put("address1", address1);
Address address2 = new Address("江西省","南昌市","阳明路","330004");
map.put("address2", address2);
Address address3 = new Address("陕西省","西安市","长安南路","710114");
map.put("address3", address3);
String jsonText = JSON.toJSONString(map, true);
System.out.println("map2Json()方法:jsonText=="+jsonText);
//输出结果:jsonText=={"address1":{"city":"深圳市","post":"580053","province":"广东省","street":"科苑南路"},"address2":{"city":"南昌市","post":"330004","province":"江西省","street":"阳明路"},"address3":{"city":"西安市","post":"710114","province":"陕西省","street":"长安南路"}}
}
/**
* json转map
*/
@Test
public void json2Map(){
String text = "{\"age\":12,\"id\":\"001\",\"name\":\"tom\"}";
Map<String,Object> map = JSON.parseObject(text);
System.out.println("json2Map()方法:map=="+map);
//输出结果:{"name":"tom","id":"001","age":12}
Set<String> set = map.keySet();
for(String key : set){
System.out.println(key+"--->"+map.get(key));
}
}
}
package com.orange.com.orange.json.fastjson;
import com.alibaba.fastjson.JSON;
public class CustomText {
/**
* touser : OPENID
* msgtype : text
* text : {"content":"Hello World"}
*/
//{"msgtype":"text","text":{"content":"Hello World"},"touser":"OPENID"}
private String touser;
private String msgtype;
private TextBean text;
public static class TextBean {
/**
* content : Hello World
*/
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public TextBean getText() {
return text;
}
public void setText(TextBean text) {
this.text = text;
}
}
class Test{
public static void main(String[] args) {
CustomText customText = new CustomText();
customText.setTouser("OPENID");
customText.setMsgtype("text");
CustomText.TextBean textBean = new CustomText.TextBean();
textBean.setContent("Hello World");
customText.setText(textBean);
String json = JSON.toJSONString(customText);
System.out.println(json);
//{"msgtype":"text","text":{"content":"Hello World"},"touser":"OPENID"}
}
/**
* {
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}
*/
}
package com.orange.com.orange.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import java.util.Set;
public class FastJsonTest1 {
public static void main(String[] args) {
String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
//第一种方式
Map maps = (Map)JSON.parse(str);
System.out.println("这个是用JSON类来解析JSON字符串!!!");
for (Object map : maps.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" " + ((Map.Entry)map).getValue());
}
//第二种方式
Map mapTypes = JSON.parseObject(str);
System.out.println("这个是用JSON类的parseObject来解析JSON字符串!!!");
for (Object obj : mapTypes.keySet()){
System.out.println("key为:"+obj+"值为:"+mapTypes.get(obj));
}
//第三种方式
Map mapType = JSON.parseObject(str,Map.class);
System.out.println("这个是用JSON类,指定解析类型,来解析JSON字符串!!!");
for (Object obj : mapType.keySet()){
System.out.println("key为:"+obj+"值为:"+mapType.get(obj));
}
//第四种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map json = (Map) JSONObject.parse(str);
System.out.println("这个是用JSONObject类的parse方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第五种方式
/**
* JSONObject是Map接口的一个实现类
*/
JSONObject jsonObject = JSONObject.parseObject(str);
System.out.println("这个是用JSONObject的parseObject方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第六种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map mapObj = JSONObject.parseObject(str,Map.class);
System.out.println("这个是用JSONObject的parseObject方法并执行返回类型来解析JSON字符串!!!");
for (Object map: json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
String strArr = "{{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}," +
"{\"00\":\"zhangsan\",\"11\":\"lisi\",\"22\":\"wangwu\",\"33\":\"maliu\"}}";
// JSONArray.parse()
System.out.println(json);
}
}
package com.orange.com.orange.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
public class FastJsonTest {
public static void main(String[] args) {
String json = "[{\"id\":1,\"type\":\"cycle\",\"attribute\":{\"center\":\"(10.4, 123.345)\", \"radius\":67.4}},{\"id\":2,\"type\":\"polygon\",\"attribute\":[{\"vertex\":\"(10.4, 133.345)\"}, {\"vertex\":\"(10.4, 143.345)\"}]}]";
JSONArray array = JSON.parseArray(json);
System.out.println(array.getJSONObject(0).getJSONObject("attribute").get("center"));
System.out.println(array.getJSONObject(1).getJSONArray("attribute").getJSONObject(1).get("vertex"));
// 输出结果为: (10.4, 123.345) (10.4, 143.345)
}
}
对于JSONArray和JSONObject而言,常用于项目中的io传输或发送http请求中参数中,因为是最接近二进制的,也防止信息丢失的一种可能,然而对于对象的形式返回给前端的话,可以通过map形式传递给前端,使用方式上存在多种可能,得具体情况具体分析了