fastjson 简单使用 及其JSONObject使用

阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:
速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parser。包括自称最快的JackJson;
功能强大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;无依赖,能够直接运行在Java SE 5.0以上版本;支持Android;开源 (Apache 2.0)

源码地址:https://github.com/alibaba/fastjson


Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。

public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
*public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
*public static final T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean
*public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
*public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
*public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。

 

maven:

    <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>

一般只用第二个fastjson就可以

 

demo:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.ArrayList;
import java.util.List;
import lombok.ToString;

public class fastjson {

    public static void main(String[] args) {
        Group group = new Group();
        group.setId(0L);
        group.setName("admin");

        User guestUser = new User();
        guestUser.setId(2L);
        guestUser.setName("guest");

        User rootUser = new User();
        rootUser.setId(3L);
        rootUser.setName("root");

        group.getUsers().add(guestUser);
        group.getUsers().add(rootUser);

        String jsonString = JSON.toJSONString(group);
        System.out.println(jsonString);
        Group group2 = JSON.parseObject(jsonString, Group.class);
        System.out.println("===============List==============");
        String strList=JSON.toJSONString(group.getUsers());
        System.out.println(strList);
        List<User> list=JSON.parseArray(strList,User.class);
        System.out.println(JSON.toJSONString(list));
        List<User> list2=JSON.parseObject(strList,new TypeReference<List<User>>(){});
        System.out.println(JSON.toJSONString(list2));
    }
}

@ToString
class User {

    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Group {

    private Long id;
    private String name;
    private List<User> users = new ArrayList<User>();

    public Long getId() {
        return id;
    }

    public void setId(Long 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;
    }
}

output:

{"id":0,"name":"admin","users":[{"id":2,"name":"guest"},{"id":3,"name":"root"}]}
Disconnected from the target VM, address: '127.0.0.1:1655', transport: 'socket'
===============List==============
[{"id":2,"name":"guest"},{"id":3,"name":"root"}]
[{"id":2,"name":"guest"},{"id":3,"name":"root"}]
[{"id":2,"name":"guest"},{"id":3,"name":"root"}]

特别注意上面的反序列化数组,有两种不同的方式。

2.查看JSONObject的使用

这个JSONObject在很多包里面都存在这个类,这里说的是fastjson包里面的使用

package com.qhong.fastjson;

//import com.alibaba.fastjson.JSONObject;


//import net.sf.json.JSONObject;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class OperatorJSON {
    public static void main(String[] args) {
        createJson();
        createJsonByMap();
        createJsonByJavaBean();
    }

    private static void createJson() {
        JSONObject obj = new JSONObject();
        obj.put("name", "John");
        obj.put("sex", "male");
        obj.put("age", 22);
        obj.put("is_student", true);
        obj.put("hobbies", new String[] {"hiking", "swimming"});
        //调用toString()方法可直接将其内容打印出来
        System.out.println(obj.toString());
    }

    private static void createJsonByMap() {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("name", "John");
        data.put("sex", "male");
        data.put("age", 22);
        data.put("is_student", true);
        data.put("hobbies", new String[] {"hiking", "swimming"});

        JSONObject obj = new JSONObject(data);
        System.out.println(obj.toString());
    }

    private static void createJsonByJavaBean() {
        PersonInfo info = new PersonInfo();
        info.setName("John");
        info.setSex("male");
        info.setAge(22);
        info.setStudent(true);
        info.setHobbies(new String[] {"hiking", "swimming"});

        String text= JSONObject.toJSONString(info);
        System.out.println(text);
//        JSONObject obj = JSONObject.toJSON(info);
//        System.out.println(obj);
    }

}

class PersonInfo {

    private String name;
    private String sex;
    private int age;
    private boolean isStudent;
    private String[] hobbies;

    public void setName(String name) {
        this.name = name;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void setStudent(boolean isStudent) {
        this.isStudent = isStudent;
    }
    public void setHobbies(String[] hobbies) {
        this.hobbies = hobbies;
    }
    //getter不能少
    public String getName() {
        return name;
    }
    public String getSex() {
        return sex;
    }
    public int getAge() {
        return age;
    }
    public boolean isStudent() {
        return isStudent;
    }
    public String[] getHobbies() {
        return hobbies;
    }
}

output:

{"hobbies":["hiking","swimming"],"sex":"male","name":"John","is_student":true,"age":22}
{"hobbies":["hiking","swimming"],"sex":"male","name":"John","is_student":true,"age":22}
{"age":22,"hobbies":["hiking","swimming"],"name":"John","sex":"male","student":true}

Process finished with exit code 0

可以从注释的区域看出,这个是fastjson包里面的,如果切换到net.sf.json包里面,那么就会报错!

 

http://blog.csdn.net/glarystar/article/details/6654494

posted @ 2017-11-03 18:06  hongdada  阅读(2017)  评论(0编辑  收藏  举报