使⽤fastjson进⾏JSONObject、JSONArray、Map、JavaBean。。。
什么是JSON?
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。
Fastjson是国内著名的电⼦商务互联⽹公司阿⾥巴巴内部开发的⽤于java后台处理json格式数据的⼀个⼯具包,包括“序列化”和“反序列化”两部分,它具备如下特征
1. 速度最快,测试表明,fastjson具有极快的性能,超越任其他的java json parser。包括⾃称最快的jackson。
2. 功能强⼤,完全⽀持java bean、集合、Map、⽇期、Enum,⽀持范型,⽀持⾃省。
3. ⽆依赖,能够直接运⾏在Java SE 5.0以上版本
4. ⽀持Android。
5. 这是fastJson的⽹址:code.alibabatech/wiki/display/FastJSON/Overview其中包含了json数据处理的教程,jar下载地址,example样例等JSONObject 与JSONArray
JSONObject
  json对象,就是⼀个键对应⼀个值,使⽤的是⼤括号{ },如:{key:value}
JSONArray
  json数组,使⽤中括号[ ],只不过数组⾥⾯的项也是json键值对格式的
  Json对象中是添加的键值对,JSONArray中添加的是Json对象
例⼦:
1public class JsonTest {
2public static void main(String[] args) {
3
4// Json对象中是添加的键值对,JSONArray中添加的是Json对象
5
6        JSONObject jsonObject = new JSONObject();
7        JSONObject jsonObject1 = new JSONObject();
8        JSONArray jsonArray = new JSONArray();
9        jsonObject1.put("001","tom");
10
11// JSONObject 对象中添加键值对
12        jsonObject.put("key","value");
13// 将JSONObject对象添加到json数组中
14        jsonArray.add(jsonObject);
15        jsonArray.add(jsonObject1);
16
17        System.out.String());
18
19// 输出结果: [{"key":"value"},{"001":"tom"}]
20
21    }
22 }
先来个官⽅例⼦
1package com.wanggs.wanggs.json.fastjson;
2
3import java.util.List;
4
5/**
6 * Created by wanggs on 2017/7/27.
7*/
8public class Group {
9private int id;
10private String name;
11    List<User> users;
12
13public int getId() {
14return id;
15    }
16
17public void setId(int id) {
18this.id = id;
19    }
20
21public String getName() {
22return name;
23    }
24
25public void setName(String name) {
26this.name = name;
27    }
28
29public List<User> getUsers() {
30return users;
31    }
32
33public void setUsers(List<User> users) {
34this.users = users;
35    }
36 }
37
38class User{
39private int id;
40private String name;
json转换对象
41
42public int getId() {
43return id;
44    }
45
46public void setId(int id) {
47this.id = id;
48    }
49
50public String getName() {
51return name;
52    }
53
54public void setName(String name) {
55this.name = name;
56    }
57 }
1import com.alibaba.fastjson.JSON;
2
3import java.util.ArrayList;
4import java.util.List;
5
6public class FastJsonTest {
7public static void main(String[] args) {
8        Group group = new Group();
9        group.setId(0);
10        group.setName("admin");
11
12        User user = new User();
13        user.setId(001);
14        user.setName("guest");
15        User user1 = new User();
16        user1.setId(002);
17        user1.setName("root");
18        List<User> users = new ArrayList<User>();
19        users.add(user);
20        users.add(user1);
21
22        group.setUsers(users);
23
24        String json = JSONString(group);
25        System.out.println(json);
26
27// 输出: {"id":0,"name":"admin","users":[{"id":1,"name":"guest"},{"id":2,"name":"root"}]}
28    }
29 }
下⾯给出fastJson处理json数据格式的代码样例:
1import com.alibaba.fastjson.JSON;
2import com.alibaba.fastjson.JSONObject;
3import com.alibaba.fastjson.serializer.SerializerFeature;
4import com.wanggs.wanggs.json.fastjson.People;
5import org.junit.Test;
6
7import static org.junit.Assert.*;
8
9public class FastJsonTestTest {
10
11/**
12    * 序列化
13*/
14    @Test
15public void toJsonString() {
16        People people = new People("001","tom",12);
17        String text = JSONString(people);
18        System.out.println(text);
19
20// 输出结果: {"age":12,"id":"001","name":"tom"}
21    }
22
23/**
24    * 反序列为Json对象
25*/
26    @Test
27public void parseJsonObject(){
28        String text = "{\"age\":12,\"id\":\"001\",\"name\":\"tom\"}";
29        People people = (People) JSON.parseObject(text,People.class);
30        System.out.println("parseBeanObject()⽅法:people==" + Id() + "," + Name() + "," + Age());
31
32// 输出结果为: parseBeanObject()⽅法:people==001,tom,12
33    }
34
35/**
36    * 将javaBean转化为json对象
37*/
38    @Test
39public void bean2Json(){
40        People people = new People("002","jack",23);
41        JSONObject jsonObject = (JSONObject) JSON(people);
42        System.out.println("bean2Json()⽅法:jsonObject==" + jsonObject);
43
44// 输出结果: bean2Json()⽅法:jsonObject=={"name":"jack","id":"002","age":23}
45    }
46
47/**
48    * 全序列化直接把java bean序列化为json⽂本之后,能够按照原来的类型反序列化回来。⽀持全序列化,需要打开SerializerFeature.WriteClassName特性49*/
50    @Test
51public void parseJSONAndBeanEachother(){
52        People people = new People("002","jack",23);
53        SerializerFeature[] featureArr = { SerializerFeature.WriteClassName };
54        String text = JSONString(people, featureArr);
55
56        System.out.println("parseJSONAndBeanEachother()⽅法:text==" + text);
57// 输出结果:parseJSONAndBeanEachother()⽅法:text=={"@type":"com.wanggs.wanggs.json.fastjson.People","age":23,"id":"002","name":"jack"}
58      People people1 = (People) JSON.parse(text);
59        System.out.println("parseJSONAndBeanEachother()⽅法:People==" + Id() + "," + Name() + "," + Age());
60// 输出结果:userObj==testFastJson001,maks,105
61    }
62 }
附:javaBean类People.java
1public class People {
2private String id;
3private String name;
4private int age;
5
6public People() {
7    }
8
9public People(String id, String name, int age) {
10this.id = id;
11this.name = name;
12this.age = age;
13    }
14
15public String getId() {
16return id;
17    }
18
19public void setId(String id) {
20this.id = id;
21    }
22
23public String getName() {
24return name;
25    }
26
27public void setName(String name) {
28this.name = name;
29    }
30
31public int getAge() {
32return age;
33    }
34
35public void setAge(int age) {
36this.age = age;
37    }
38 }
再深⼊Json
1import com.alibaba.fastjson.JSON;
2import com.alibaba.fastjson.JSONArray;
3import com.wanggs.wanggs.json.fastjson.Address;
4import com.wanggs.wanggs.json.fastjson.People;
5import org.junit.Test;
6
7import java.util.*;
8
9import static org.junit.Assert.*;
10
11/**
12 * Created by wanggs on 2017/7/27.
13*/
14public class FastJsonTest1Test {
15/**
16    * 数组转json字符串
17*/
18    @Test
19public void array2Json() {
20        String[] arr = {"bill", "green", "maks", "jim"};
21        String jsonText = JSONString(arr);
22        System.out.println("array2Json()⽅法:jsonText==" + jsonText);
23// 输出结果:jsonText==["bill","green","maks","jim"]
24    }
25
26/**
27    * json格式字符串转数组
28*/
29    @Test
30public void json2Array() {
31        String jsonText = "[\"bill\",\"green\",\"maks\",\"jim\"]";
32        JSONArray jsonArray = JSON.parseArray(jsonText);
33        System.out.println("json2Array()⽅法:jsonArray==" + jsonArray);
34// 输出结果:jsonArray==["bill","green","maks","jim"]
35    }
36
37/**
38    * 数组转json格式字符串
39*/
40    @Test
41public void array2Json2() {
42        People people = new People("001", "tom", 12);
43        People people1 = new People("002", "jack", 23);
44        People people2 = new People("003", "mair", 22);
45
46        People[] peoples = new People[]{people, people1, people2};
47
48        String jsonText = JSONString(peoples);
49        System.out.println("array2Json2()⽅法:jsonText==" + jsonText);
50
51//输出结果:array2Json2()⽅法:jsonText==[{"age":12,"id":"001","name":"tom"},{"age":23,"id":"002","name":"jack"},{"age":22,"id":"003","name":"mair"}]
52
53    }
54
55/**
56    * json格式字符串转数组
57*/
58    @Test
59public void json2Array2() {
60        String jsonText = "[{\"age\":12,\"id\":\"001\",\"name\":\"tom\"},{\"age\":23,\"id\":\"002\",\"name\":\"jack\"},{\"age\":22,\"id\":\"003\",\"name\":\"mair\"}]";
61        JSONArray jsonArr = JSON.parseArray(jsonText);
62        System.out.println("json2Array2()⽅法:jsonArr==" + jsonArr);
63// 输出结果:json2Array2()⽅法:jsonArr==[{"name":"tom","id":"001","age":12},{"name":"jack","id":"002","age":23},{"name":"mair","id":"003","age":22}]
64
65    }
66
67/**
68    * list集合转json格式字符串
69*/
70    @Test
71public void list2Json() {
72        List<People> list = new ArrayList<People>();
73        list.add(new People("001", "tom", 12));
74        list.add(new People("002", "jack", 23));
75        list.add(new People("003", "mair", 22));
76
77        String jsonText = JSONString(list);
78        System.out.println("list2Json()⽅法:jsonText==" + jsonText);
79
80// 输出的结果为: [{"age":12,"id":"001","name":"tom"},{"age":23,"id":"002","name":"jack"},{"age":22,"id":"003","name":"mair"}]
81    }
82
83
84/**
85    * map转json格式字符串
86*/
87    @Test
88public void map2Json() {
89        Map map = new HashMap();
90        Address address1 = new Address("⼴东省","深圳市","科苑南路","580053");
91        map.put("address1", address1);
92        Address address2 = new Address("江西省","南昌市","阳明路","330004");
93        map.put("address2", address2);
94        Address address3 = new Address("陕西省","西安市","长安南路","710114");
95        map.put("address3", address3);
96        String jsonText = JSONString(map, true);
97        System.out.println("map2Json()⽅法:jsonText=="+jsonText);
98//输出结果:jsonText=={"address1":{"city":"深圳市","post":"580053","province":"⼴东省","street":"科
苑南路"},"address2":{"city":"南昌市","post":"330004","province":"江西省","street":"阳明路"},"address3":{"city":"西安市","post":"710114","
99    }
100
101/**
102    * json转map
103*/
104    @Test
105public void json2Map(){
106        String text = "{\"age\":12,\"id\":\"001\",\"name\":\"tom\"}";
107        Map<String,Object> map = JSON.parseObject(text);
108        System.out.println("json2Map()⽅法:map=="+map);
109//输出结果:{"name":"tom","id":"001","age":12}
110        Set<String> set = map.keySet();
111for(String key : set){
112            System.out.println(key+"--->"+(key));
113        }
114    }
115 }
1import com.alibaba.fastjson.JSON;
2
3
4 5
6public class CustomText {
7
8/**
9    * touser : OPENID
10    * msgtype : text
11    * text : {"content":"Hello World"}
12*/
13//{"msgtype":"text","text":{"content":"Hello World"},"touser":"OPENID"}
14private String touser;
15private String msgtype;
16private TextBean text;
17
18public static class TextBean {
19/**
20        * content : Hello World
21*/
22
23private String content;
24
25public String getContent() {
26return content;
27        }
28
29public void setContent(String content) {
31        }
32    }
33public String getTouser() {
34return touser;
35    }
36
37public void setTouser(String touser) {
39    }
40
41public String getMsgtype() {
42return msgtype;
43    }
44
45public void setMsgtype(String msgtype) {
46this.msgtype = msgtype;
47    }
48
49public TextBean getText() {
50return text;
51    }
52
53public void setText(TextBean text) {
< = text;
55    }
56 }
57
58class Test{
59public static void main(String[] args) {
60        CustomText customText = new CustomText();
61        customText.setTouser("OPENID");
62        customText.setMsgtype("text");
63        CustomText.TextBean textBean =  new CustomText.TextBean();
64        textBean.setContent("Hello World");
65        customText.setText(textBean);
66
67        String json = JSONString(customText);
68        System.out.println(json);
69//{"msgtype":"text","text":{"content":"Hello World"},"touser":"OPENID"}
70    }
71/**
72    * {
73    "touser":"OPENID",
74    "msgtype":"text",
75    "text":
76    {
77    "content":"Hello World"
78    }
79    }
80*/
81    }
归纳六种⽅式json转map
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import java.util.Set;
/**
* Created by wanggs on 2017/7/27.
*/
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 : Set()){
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+"值为:"+(obj));
}
//第三种⽅式
Map mapType = JSON.parseObject(str,Map.class);
System.out.println("这个是⽤JSON类,指定解析类型,来解析JSON字符串");
for (Object obj : mapType.keySet()){
System.out.println("key为:"+obj+"值为:"+(obj));
}
//第四种⽅式
/**
* JSONObject是Map接⼝的⼀个实现类
*/
Map json = (Map) JSONObject.parse(str);
System.out.println("这个是⽤JSONObject类的parse⽅法来解析JSON字符串");
for (Object map : Set()){
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 : Set()){
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: Set()){
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);
}
}
1import com.alibaba.fastjson.JSON;
2import com.alibaba.fastjson.JSONArray;
3import com.alibaba.fastjson.JSONObject;
4
5import java.util.*;
6
7
8public class FastJsonTest {
9public static void main(String[] args) {
10
11        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)\"}]}]"; 12
13        JSONArray array = JSON.parseArray(json);
14
15        System.out.JSONObject(0).getJSONObject("attribute").get("center"));
16
17        System.out.JSONObject(1).getJSONArray("attribute").getJSONObject(1).get(
"vertex"));
18
19// 输出结果为: (10.4, 123.345) (10.4, 143.345)
20    }
21 }
22
⽅法总结
4.JSONObject、JSONArray,Map转String
JSONObject——String:
System.out.println(myJsonObject);//可直接输出JSONObject的内容
JSONArray——String:
System.out.println(myJsonArray);//可直接输出myJsonArray的内容
Map——String:
System.out.println(map);//可直接输出map的内容
5.JSONObject转JSONArray
JSONObject myJson = JSONObject.fromObject(jsonString);
Map m = myJson;
7.JSONArray转JSONObject
for(int i=0 ; i < myJsonArray.length() ;i++)
{
//获取每⼀个JsonObject对象
JSONObject myjObject = JSONObject(i);
}
8.JSONArray转Map
9.Map转JSONObject
JSONObject json = JSONObject.fromObject( map );
10.Map转JSONArray
JSONArray.fromObject(map);
11.List转JSONArray
JSONArray jsonArray2 = JSONArray.fromObject( list );
1 1.String转JSONObject
2
3(1)json-lib(即net.sf.json.JSONObject)
4
5 String jsonMessage = "{\"语⽂\":\"88\",\"数学\":\"78\",\"计算机\":\"99\"}";
6
7 JSONObject  myJson = JSONObject.fromObject(jsonMessage);
8
9(2).⽤阿⾥巴巴的fastjson的jar包
10
11 String str = "{\"baid\":null,\"32d3:\":\"null\",433:\"0x32\",032:\"ju9fw\"}";
12 com.alibaba.fastjson.JSONObject jm = com.alibaba.fastjson.JSON.parseObject(str);
13
14 2.String转JSONArray
15
16 String jsonMessage = "[{'num':'成绩', '外语':88, '历史':65, '地理':99, 'object':{'aaa':'1111','bbb':'2222','cccc':'3333'}}," +

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。