Gson和Fastjson的使用

转载自:JSON技术的调研报告

一、Google的Gson包的使用简单介绍。

Gson类:解析json的最基础的工具类
JsonParser类:解析器来解析JSON到JsonElements的解析树
JsonElement类:一个类代表的JSON元素
JsonObject类:JSON对象类型
JsonArray类:JsonObject数组
TypeToken类:用于创建type,比方泛型List

(1)maven依赖

com.google.code.gson
gson
2.3.1

开源地址 https://github.com/google/gson

(2)基础转换类

    public class Book {
        private String id;
        private String name;

        public Book() {
            super();
        }

        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 class Student {
        private String name;
        private int age;
        private String sex;
        private String describe;
        private Set books;

        public Student() {
            super();
        }

        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;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public Set getBooks() {
            return books;
        }

        public void setBooks(Set books) {
            this.books = books;
        }

        public String getDescribe() {
            return describe;
        }

        public void setDescribe(String describe) {
            this.describe = describe;
        }
    }

(3)bean转换json

Gson gson = new Gson();
String json = gson.toJson(obj);

obj是对象

(4)json转换bean

Gson gson = new Gson();
String json = "{"id":"2","name":"Json技术"}";
Book book = gson.fromJson(json, Book.class);

(5)json转换复杂的bean,比方List。Set

将json转换成复杂类型的bean,须要使用TypeToken

String json = "[{"id":"1","name":"Json技术"},{"id":"2","name":"java技术"}]";

//将json转换成List
List list = gson.fromJson(json,new TypeToken<LIST>() {}.getType());
//将json转换成Set
Set set = gson.fromJson(json,new TypeToken<SET>() {}.getType());

(6)通过json对象直接操作json以及一些json的工具

a)格式化Json

String json = "[{"id":"1","name":"Json技术"},{"id":"2","name":"java技术"}]";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(json);
json = gson.toJson(je);

b)推断字符串是否是json,通过捕捉的异常来推断是否是json

        String json = "[{"id":"1","name":"Json技术"},{"id":"2","name":"java技术"}]";
        boolean jsonFlag;
        try {
            new JsonParser().parse(str).getAsJsonObject();
            jsonFlag = true;
        } catch (Exception e) {
            jsonFlag = false;
        }

c)从json串中获取属性

String json = "{"id":"1","name":"Json技术"}";
String propertyName = 'id';
String propertyValue = "";
try {
    JsonParser jsonParser = new JsonParser();
    JsonElement element = jsonParser.parse(json);
    JsonObject jsonObj = element.getAsJsonObject();
    propertyValue = jsonObj.get(propertyName).toString();
} catch (Exception e) {
    propertyValue = null;
}

d)除去json中的某个属性

String json = "{"id":"1","name":"Json技术"}";
String propertyName = 'id';
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.remove(propertyName);
json = jsonObj.toString();

e)向json中加入属性

String json = "{"id":"1","name":"Json技术"}";
String propertyName = 'desc';
Object propertyValue = "json各种技术的调研";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
json = jsonObj.toString();

f)改动json中的属性

String json = "{"id":"1","name":"Json技术"}";
String propertyName = 'name';
Object propertyValue = "json各种技术的调研";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.remove(propertyName);
jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
json = jsonObj.toString();

g)推断json中是否有属性

String json = "{"id":"1","name":"Json技术"}";
String propertyName = 'name';
boolean isContains = false ;
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
isContains = jsonObj.has(propertyName);

h)json中日期格式的处理

GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Gson gson = builder.create();

然后使用gson对象进行json的处理,假设出现日期Date类的对象,就会依照设置的格式进行处理

i)json中对于Html的转义

Gson gson = new Gson();
这样的对象默认对Html进行转义,假设不想转义使用以下的方法

GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
Gson gson = builder.create();

二、阿里巴巴的FastJson包的使用简单介绍。

(1)maven依赖

com.alibaba
fastjson
1.2.7
开源地址 https://github.com/alibaba/fastjson

(2)基础转换类

同上

(3)bean转换json

将对象转换成格式化的json
JSON.toJSONString(obj,true);
将对象转换成非格式化的json
JSON.toJSONString(obj,false);
obj设计对象
对于复杂类型的转换,对于反复的引用在转成json串后在json串中出现引用的字符,比方
$ref":"$[0].books[1]

Student stu = new Student();
Set books= new HashSet();
Book book = new Book();
books.add(book);
stu.setBooks(books);
List list = new ArrayList();
for(int i=0;i<5;i++)
list.add(stu);
String json = JSON.toJSONString(list,true);

(4)json转换bean

String json = "{"id":"2","name":"Json技术"}";
Book book = JSON.parseObject(json, Book.class);

(5)json转换复杂的bean,比方List,Map

//将json转换成List
List list = JSON.parseObject(json,new TypeReference<ARRAYLIST>(){});
//将json转换成Set
Set set = JSON.parseObject(json,new TypeReference<HASHSET>(){});

(6)通过json对象直接操作json

a)从json串中获取属性

String propertyName = 'id';
String propertyValue = "";
String json = "{"id":"1","name":"Json技术"}";
JSONObject obj = JSON.parseObject(json);
propertyValue = obj.get(propertyName));

b)除去json中的某个属性

String propertyName = 'id';
String propertyValue = "";
String json = "{"id":"1","name":"Json技术"}";
JSONObject obj = JSON.parseObject(json);
Set set = obj.keySet();
propertyValue = set.remove(propertyName);
json = obj.toString();

c)向json中加入属性

String propertyName = 'desc';
Object propertyValue = "json的玩意儿";
String json = "{"id":"1","name":"Json技术"}";
JSONObject obj = JSON.parseObject(json);
obj.put(propertyName, JSON.toJSONString(propertyValue));
json = obj.toString();

d)改动json中的属性

String propertyName = 'name';
Object propertyValue = "json的玩意儿";
String json = "{"id":"1","name":"Json技术"}";
JSONObject obj = JSON.parseObject(json);
Set set = obj.keySet();
if(set.contains(propertyName))
obj.put(propertyName, JSON.toJSONString(propertyValue));
json = obj.toString();

e)推断json中是否有属性

String propertyName = 'name';
boolean isContain = false;
String json = "{"id":"1","name":"Json技术"}";
JSONObject obj = JSON.parseObject(json);
Set set = obj.keySet();
isContain = set.contains(propertyName);

f)json中日期格式的处理

Object obj = new Date();
String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss.SSS");

使用JSON.toJSONStringWithDateFormat,该方法能够使用设置的日期格式对日期进行转换

原文地址:https://www.cnblogs.com/lxjshuju/p/7248297.html