java Json 技术记录

1.Json-lib

json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,包括commons-beanutils.jar,commons-collections.jar,commons-lang.jar,commons-logging.jar,ezmorph-1.0.6.jar,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷,比如一个类里面会出现另一个类的list或者map集合,json-lib从json到bean的转换就会出现问题。json-lib在功能和性能上面都不能满足现在互联网化的需求。

2.Gson

Gson是目前功能最全的Json解析神器,Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或用户应用。Gson的应用主要为toJson与fromJson两个转换函数,无依赖,不需要例外额外的jar,能够直接跑在JDK上。
而在使用这种对象转换之前需先创建好对象的类型以及其成员才能成功的将JSON字符串成功转换成相对应的对象。类里面只要有get和set方法,Gson完全可以将复杂类型的json到bean或bean到json的转换,是JSON解析的神器。

Gson在功能上面无可挑剔,但是性能上面比FastJson有所差距。

3.fastjson

Fastjson是一个Java语言编写的高性能的JSON处理器,由阿里巴巴公司开发。无依赖,不需要例外额外的jar,能够直接跑在JDK上。FastJson在复杂类型的Bean转换Json上会出现一些问题,可能会出现引用的类型,导致Json转换出错,需要制定引用。

FastJson采用独创的算法,将parse的速度提升到极致,超过所有json库。

4.jackJson

相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。Jackson对于复杂类型的json转换bean会出现问题,一些集合Map,List的转换出现问题。Jackson对于复杂类型的bean转换Json,转换的json格式不是标准的Json格式。

相关maven依赖

  <!--jsonLib-->
        <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.3</version>
            <classifier>jdk15</classifier>
        </dependency>

        <!--Gson-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3.1</version>
        </dependency>
        <!--fastJson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--jackSon-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.0</version>
        </dependency>
    </dependencies>

1.Json-lib 使用方法

package com.jxufe.study.jsonstudy.test;

import com.jxufe.study.jsonstudy.model.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.junit.Test;

import java.util.*;

public class JsonLibTest {
    @Test
    public void beanToJson()
    {
        User user = new User("zengting",25,new Date(),"[email protected]");
        JSONObject jsonObject = JSONObject.fromObject(user);
        System.out.println(jsonObject.toString());
    }
    @Test
    public void jsonToBean()
    {
        String json = "{\"age\":25,\"birthday\":{\"date\":7,\"day\":4,\"hours\":18,\"minutes\":7,\"month\":11,\"seconds\":23,\"time\":1512641243792,\"timezoneOffset\":-480,\"year\":117},\"email\":\"[email protected]\",\"name\":\"zengting\"}\n";
        JSONObject jsonObject = JSONObject.fromObject(json);
        User user = (User) JSONObject.toBean(jsonObject,User.class);
        System.out.println(user);
    }

    @Test
    public void listToJson()
    {
        List<User> usersList = new ArrayList<User>();
        usersList.add(new User("zengting",23,new Date(),"[email protected]"));
        usersList.add(new User("mindong",23,new Date(),"[email protected]"));
        usersList.add(new User("liliang",21,new Date(),"[email protected]"));
        String jsonString = JSONArray.fromObject(usersList).toString();
        System.out.println(jsonString);
    }
    @Test
    public void jsonToList()
    {
        List<User> usersList = new ArrayList<User>();
        usersList.add(new User("zengting",23,null,"[email protected]"));
        usersList.add(new User("mindong",23,null,"[email protected]"));
        String jsonString = JSONArray.fromObject(usersList).toString();
        System.out.println(jsonString);

        JSONArray jsonArray =  JSONArray.fromObject(jsonString);
        List<User> list = JSONArray.toList(jsonArray, new User(),new JsonConfig());
        for (User user : list) {
        System.out.println(user);
    }
    }
    @Test
    public void JsonToArray() {
        String jsonString = "[{\"age\":23,\"birthday\":null,\"email\":\"[email protected]\",\"name\":\"zengting\"},{\"age\":23,\"birthday\":null,\"email\":\"[email protected]\",\"name\":\"mindong\"}]";
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        Object[] obj = (Object[]) JSONArray.toArray(jsonArray, User.class);
        for (int i = 0; i < obj.length; i++) {
            System.out.println((User) obj[i]);
        }
    }

    // Map to Json
    @Test
    public void MapToJson() {
        Map<String, User> map = new HashMap<String, User>();
        map.put("person1", new User("zengting",23,null,"[email protected]"));
        map.put("person2", new User("mindong",23,null,"[email protected]"));
        String json = JSONObject.fromObject(map).toString();
        System.out.println(json);
    }

    // Json to map
    @Test
    public void JsonToMap() {
        String jsonStr = "{\"person2\":{\"age\":23,\"birthday\":null,\"email\":\"[email protected]\",\"name\":\"mindong\"},\"person1\":{\"age\":23,\"birthday\":null,\"email\":\"[email protected]\",\"name\":\"zengting\"}}";
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        Map<String,User> map = new HashMap<String,User>();
        for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
            String key = (String) iter.next();
            map.put(key,(User)JSONObject.toBean((JSONObject) jsonObject.get(key),User.class));
        }
        for(String key : map.keySet()){
            System.out.println((User)map.get(key));
        }
    }
}

2.Gson使用方法

package com.jxufe.study.jsonstudy.test;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jxufe.study.jsonstudy.model.User;
import org.junit.Test;

import java.lang.reflect.Type;
import java.util.*;

public class GsonTest {
    private Gson gson = new Gson();
    @Test
    public void jsonToBean()
    {
        String jsonStr = "{\"name\":\"zengting\",\"age\":23,\"birthday\":\"Dec 7, 2017 3:54:28 PM\",\"email\":\"[email protected]\"}";
        User user = gson.fromJson(jsonStr,User.class);
        System.out.println(user);
    }
    @Test
    public void beanToJson()
    {
        User user = new User("zengting",23,new Date(),"[email protected]");
        System.out.println(gson.toJson(user));
    }
    @Test
    public void listToJson()
    {
        List<User> usersList = new ArrayList<User>();
        usersList.add(new User("zengting",23,new Date(),"[email protected]"));
        usersList.add(new User("mindong",23,new Date(),"[email protected]"));
        usersList.add(new User("liliang",21,new Date(),"[email protected]"));

        System.out.println(gson.toJson(usersList));
    }
    @Test
    public void jsonToList()
    {
        String jsonList = "[{\"name\":\"zengting\",\"age\":23,\"birthday\":\"Dec 7, 2017 4:00:58 PM\",\"email\":\"[email protected]\"},{\"name\":\"mindong\",\"age\":23,\"birthday\":\"Dec 7, 2017 4:00:58 PM\"," +
                "\"email\":\"[email protected]\"},{\"name\":\"liliang\",\"age\":21,\"birthday\":\"Dec 7, 2017 4:00:58 PM\",\"email\":\"[email protected]\"}]";

        Type type = new TypeToken<ArrayList<User>>() {
        }.getType();
        List<User> userList = gson.fromJson(jsonList,type);
        System.out.println(userList);

    }

    @Test
    public void mapToJson()
    {
        Map<Integer,User>  userMap = new HashMap<Integer, User>();
        userMap.put(1,new User("zengting",23,new Date(),"[email protected]"));
        userMap.put(1,new User("mindong",22,new Date(),"[email protected]"));
        userMap.put(1,new User("liliang",25,new Date(),"[email protected]"));
        System.out.println(gson.toJson(userMap));
    }
    @Test
    public void jsonToMap()
    {
        String json = "{\"1\":{\"name\":\"liliang\",\"age\":25,\"birthday\":\"Dec 7, 2017 4:05:56 PM\",\"email\":\"[email protected]\"}}\n";
        Type type = new TypeToken<HashMap<Integer,User>>(){}.getType();
        System.out.println(gson.fromJson(json,type));
    }
    @Test
    public void listStringToJson()
    {
        List<String> strings = new ArrayList<String>();
        strings.add("json");
        strings.add("mindong");
        strings.add("liliang");
        System.out.println(gson.toJson(strings));
        System.out.println(gson.toJson("zhenghong"));
    }

}

3.fastjson 使用

package com.jxufe.study.jsonstudy.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jxufe.study.jsonstudy.model.User;
import org.junit.Test;

import java.util.*;

/**
 * @author hong.zheng
 * @Description
 * @date 2017-12-07-16:14
 **/
public class FastJsonTest {
    @Test
    public void beanToJson()
    {
        System.out.println(JSON.toJSON(new User("mindong",11,new Date(),"123")));
        System.out.println(JSON.toJSON("zhenghong"));
    }
    @Test
    public void jsonToBean()
    {
        String jsonStr = "{\"birthday\":1512634693590,\"name\":\"mindong\",\"age\":11,\"email\":\"123\",\"testName\":\"Today is 2017-12-07\"}\n";
        System.out.println(JSON.parseObject(jsonStr,User.class));
    }
    @Test
    public void testJsonToList()
    {
        List<User> usersList = new ArrayList<User>();
        usersList.add(new User("zengting",23,new Date(),"[email protected]"));
        usersList.add(new User("mindong",23,new Date(),"[email protected]"));
        usersList.add(new User("liliang",21,new Date(),"[email protected]"));
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
        String jsonList = JSON.toJSONString(usersList, SerializerFeature.WriteDateUseDateFormat);
        System.out.println(jsonList);

        System.out.println("------------------------------------------------------------------");
        List<User> list =  JSON.parseArray(jsonList,User.class);
        System.out.println(list);

        System.out.println("------------------------------------------------------------------");
        System.out.println( JSON.parseObject(jsonList,new TypeReference<List<User>>(){}));
    }

    @Test
    public void testMapToJson()
    {
        Map<Integer,User> userMap = new HashMap<Integer, User>();
        userMap.put(1,new User("zengting",23,new Date(),"[email protected]"));
        userMap.put(2,new User("mindong",22,new Date(),"[email protected]"));
        userMap.put(3,new User("liliang",25,new Date(),"[email protected]"));
        String jsonMap = JSON.toJSONString(userMap);
        System.out.println(jsonMap);

        Map<Integer,User> fromJsonMap  = JSON.parseObject(jsonMap,new TypeReference<Map<Integer, User>>(){});
        System.out.println(fromJsonMap);
    }

}

4.jackson-lib 使用


package com.jxufe.study.jsonstudy.test;

import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;import com.jxufe.study.jsonstudy.model.User;import org.junit.Test;

import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Map;

/** * @author hong.zheng * @Description * @date 2017-12-08-9:29 **/public class JacksonTest {    @Test    public void beanToJson() throws JsonProcessingException {        ObjectMapper objectMapper = new ObjectMapper();        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);        //writeObject可以转换java对象,eg:JavaBean/Map/List/Array等        User user = new User("zengting",23,new Date(),"[email protected]");        String jsonString = objectMapper.writeValueAsString(user);        System.out.println(jsonString);    }    @Test    public void jsonToBean () throws IOException {        ObjectMapper objectMapper = new ObjectMapper();

String jsonString = "{\"name\":\"zengting\",\"age\":23,\"birthday\":1512696816772,\"email\":\"[email protected]\",\"1TestName\":\"Today is 2017-12-07\"}\n";        User user = objectMapper.readValue(jsonString, User.class);        System.out.println(user);    }    @Test    public void listToJson() throws IOException {        List<User> list =  new ArrayList<User>();        list.add(new User("mindong",31,new Date(),"1321"));        list.add(new User("zengting",31,new Date(),"1321"));        list.add(new User("liliang",31,new Date(),"1321"));        ObjectMapper objectMapper = new ObjectMapper();        objectMapper.writeValue(System.out,list);

}    @Test    public void jsonTolist() throws IOException {        String json = "[{\"name\":\"mindong\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"zengting\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"liliang\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"}]";        ObjectMapper objectMapper = new ObjectMapper();        List<User> list = objectMapper.readValue(json ,List.class);        for (int i = 0; i <list.size() ; i++) {            User user =  list.get(i); // 转化失败,List<User> 的值是List<LinkedHashMap<String,Object>>,LinkedHashMap<String,Object>不能转化为User            System.out.println(list.get(i));        }    }    @Test    public void jsonTolist1() throws IOException {        String json = "[{\"name\":\"mindong\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"zengting\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"liliang\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"}]";        ObjectMapper objectMapper = new ObjectMapper();        List<Map<String,Object>> list = objectMapper.readValue(json ,List.class);        for (int i = 0; i <list.size() ; i++) {            Map<String,Object> map = list.get(i);            String name = map.get("name").toString();            Integer age = Integer.valueOf(map.get("age").toString());            Date date =  new Date(Long.valueOf(map.get("birthday").toString()));            String email = map.get("email").toString();            User user = new User(name,age,date,email);            System.out.println(user);        }    }    @Test    public void jsonToArray() throws IOException {        String json = "[{\"name\":\"mindong\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"zengting\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"liliang\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"}]";        ObjectMapper objectMapper = new ObjectMapper();        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

User []users = objectMapper.readValue(json ,User[].class);        for (int i = 0; i <users.length ; i++) {            User user =   users[i];            System.out.println(user.getClass());            System.out.println(users[i]);        }    }

}

四种解析方式对Date类型的解析不太一样

package com.jxufe.study.jsonstudy.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.sf.json.JSONObject;
import org.junit.Test;

import java.io.IOException;
import java.util.Date;

/**
 * @author hong.zheng
 * @Description
 * @date 2017-12-08-10:31
 **/
public class DateCompare {
    @Test
    public void jsonLibDate()
    {
        JSONObject jsonObject =  JSONObject.fromObject(new Date());
        System.out.println(jsonObject.toString());
        //输出 {"date":8,"day":5,"hours":11,"minutes":7,"month":11,"seconds":2,"time":1512702422553,"timezoneOffset":-480,"year":117}

    }
    @Test
    public void fastJsonDate()
    {
        System.out.println(JSON.toJSON(new Date()));
        //输出 Fri Dec 08 11:07:14 CST 2017
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
        String jsonDate = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);
        System.out.println(jsonDate);
        //"2017-12-08"
    }
    @Test
    public void GsonDate()
    {
        Gson gson = new Gson();
        System.out.println(gson.toJson(new Date()));
        //输出 "Dec 8, 2017 11:07:34 AM"
        gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        System.out.println(gson.toJson(new Date()));
        //输出  "2017-12-08"

    }
    @Test
    public void jacksonDate() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(System.out,new Date());
        //输出 1512702466576

    }
}

JsonLib 和 Jackson

package com.jxufe.study.jsonstudy.test;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.jxufe.study.jsonstudy.model.User;
import com.jxufe.study.jsonstudy.model.OtherBean;

import net.sf.json.JSONObject;
import org.junit.Test;

import java.io.IOException;
import java.util.Date;

/**
 * @author hong.zheng
 * @Description
 * @date 2017-12-08-11:26
 **/
public class OtherJson {
    @Test
    public void jsonLibTest()
    {
        OtherBean otherBean = new OtherBean();
        otherBean.setName("mindong");
        JSONObject jsonObject = JSONObject.fromObject(otherBean);
        System.out.println(jsonObject.toString());
        //{"name":"mindong","otherName":"getMethod"} 会调用 以Get开头的方法,生成Json
    }
    @Test
    public void jacksonTest() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        OtherBean otherBean = new OtherBean();
        otherBean.setName("xiaoting");
        objectMapper.writeValue(System.out,otherBean);
        // 输出  {"name":"xiaoting","myName":"mindong"} 会调用 以Get开头的方法,生成Json
    }
}
时间: 2024-10-10 04:30:43

java Json 技术记录的相关文章

(转)java缓存技术,记录

http://blog.csdn.net/madun/article/details/8569860 最近再ITEYE上看到关于讨论JAVA缓存技术的帖子比较多,自己不懂,所以上网大概搜了下,找到一篇,暂作保存,后面如果有用到可以参考.此为转贴,帖子来处:http://cogipard.info/articles/cache-static-files-with-jnotify-and-ehcache 介绍 JNotify:http://jnotify.sourceforge.net/,通过JNI

浅谈Java分页技术

话不多言.我们要实现java分页技术,我们首先就需要定义四个变量,他们是: int  pageSize;//每页显示多少条记录 int pageNow;//希望现实第几页 int pageCount;//一共有多少页 int rowCount;//一共有多少条记录 说明: 1.pageSize是指定的 2.pageNow是用户选择的 3.rowCount是从表中查询得到的 4.pageCount是计算得到的,该计算为: if(rowCount%pageSize==0) { pageCount=r

javascript中字符串格式转化成json对象记录

什么是JSON JSON(JavaScript Object Notation)是一种优美的JavaScript对象创建方法.JSON也是一种轻量级数据交换格式.JSON非常易于人阅读与编写,同时利于机器解析与生成.JSON是在AJAX中代替XML交换数据的更佳方案. JSON格式与语法 var jsonobject= {         //对象内的属性语法(属性名与属性值是成对出现的)         propertyname:value, //对象内的函数语法(函数名与函数内容是成对出现的

各个JSON技术的比较

JSON技术的调研报告 一 .各个JSON技术的简介和优劣1.json-libjson-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,包括commons-beanutils.jar,commons-collections-3.2.jar,commons-lang-2.6.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷,比如

各个JSON技术的比较(Jackson,Gson,Fastjson)的对比

JSON技术的调研报告 一 .各个JSON技术的简介和优劣 1.json-lib json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包, 包括commons-beanutils.jar,commons-collections-3.2.jar,commons-lang-2.6.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar, 对于复杂类型的转换,json-lib对于json转换成bean还有缺

Java序列化技术与Protobuff

前言: Java序列化是Java技术体系当中的一个重要议题,序列化的意义在于信息的交换和存储,通常会和io.持久化.rmi技术有关(eg:一些orm框架会要求持久化的对象类型实现Serializable接口). 本文将提供Java自带序列化机制和ProtoStuff的序列化(仅仅当作一种数据格式)的比较,从序列化的内容和特点来对二者进行比较. 结论:1,Java序列化对象时不需要通过属性的get set方法或其它无关序列化内部定义的方法(比如readObject,writeObject是内置的序

【Java】Java Servlet 技术简介

Java 开发人员兼培训师 Roy Miller 将我们现有的 servlet 介绍资料修改成了这篇易于学习的实用教程.Roy 将介绍并解释 servlet 是什么,它们是如何工作的,如何使用它们来创建您能够想像到的任意复杂度的 Web 应用程序,以及作为一名专业编程人员,您如何才能最有效地使用 servlet. 5 评论: Roy W. Miller ([email protected]), 独立的软件开发辅导员.程序员和作者, RoleModel Software 2004 年 12 月 2

小怪兽 Java反射技术 等你来打

Java反射技术,是java的难点,也是程序员进化过程中的必打小怪兽,这里就根据java api好好研究一下java的反射技术. Class Fields Methods 请先回忆一下[java类的定义]. 一.反射是什么 反射是什么?百度百科这样定义:JAVA反射机制是在运行状态下,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取对象信息以及动态调用对象方法的功能称为java语言的反射机制. 可以这样理解,大家小时候有木有玩过平

Java Servlet 技术简介

Java Servlet 技术简介 Java 开发人员兼培训师 Roy Miller 将我们现有的 servlet 介绍资料修改成了这篇易于学习的实用教程.Roy 将介绍并解释 servlet 是什么,它们是如何工作的,如何使用它们来创建您能够想像到的任意复杂度的 Web 应用程序,以及作为一名专业编程人员,您如何才能最有效地使用 servlet. 4 评论: Roy W. Miller ([email protected]), 独立的软件开发辅导员.程序员和作者, RoleModel Soft