JSON的解析[Java-JSON、FastJSON、GSON]

Java-Json

一、   JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。
 Json建构于两种结构:
     1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 如:     
        {
            “name”:”jackson”,
            “age”:100
         }


    2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)如:
     {
        “students”:
        [
            {“name”:”jackson”,“age”:100},
            {“name”:”michael”,”age”:51}
        ]
     }
二、java解析JSON步骤
    A、服务器端将数据转换成json字符串
      首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:http://json-lib.sourceforge.net/
 
 JSON的解析[Java-JSON、FastJSON、GSON]_第1张图片
    然后将数据转为json字符串,核心函数是:
 public static String createJsonString(String key, Object value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();

    }
B、客户端将json字符串转换为相应的javaBean
   1、客户端获取json字符串因为android项目中已经集成了json的jar包所以这里无需导入
public class HttpUtil
{
   
    public static String getJsonContent(String urlStr)
    {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

   
    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}

2、获取javaBean
    public static Person getPerson(String jsonStr)
    {
        Person person = new Person();
        try
        {// 将json字符串转换为json对象
            JSONObject jsonObj = new JSONObject(jsonStr);
            // 得到指定json key对象的value对象
            JSONObject personObj = jsonObj.getJSONObject("person");

            // 获取之对象的所有属性
            person.setId(personObj.getInt("id"));
            person.setName(personObj.getString("name"));
            person.setAddress(personObj.getString("address"));
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return person;
    }

    public static List<Person> getPersons(String jsonStr)
    {
        List<Person> list = new ArrayList<Person>();

        JSONObject jsonObj;
        try
        {// 将json字符串转换为json对象
            jsonObj = new JSONObject(jsonStr);
            // 得到指定json key对象的value对象
            JSONArray personList = jsonObj.getJSONArray("persons");
            // 遍历jsonArray
            for (int i = 0; i < personList.length(); i++)
            {
                // 获取每一个json对象
                JSONObject jsonItem = personList.getJSONObject(i);

                // 获取每一个json对象的值
                Person person = new Person();
                person.setId(jsonItem.getInt("id"));
                person.setName(jsonItem.getString("name"));
                person.setAddress(jsonItem.getString("address"));
                list.add(person);
            }
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }


Fastjson介绍

Fastjson是一个Java语言编写的JSON处理器,由阿里巴巴公司开发。
1、遵循
http://json.org标准,为其官方网站收录的参考实现之一。
2、功能qiang打,支持JDK的各种类型,包括基本的JavaBean、Collection、Map、Date、Enum、泛型。
3、无依赖,不需要例外额外的jar,能够直接跑在JDK上。
4、开源,使用Apache License 2.0协议开源。
http://code.alibabatech.com/wiki/display/FastJSON/Home
5、具有超高的性能,java世界里没有其他的json库能够和fastjson可相比了。


如果获得Fastjson?
SVN:
http://code.alibabatech.com/svn/fastjson/trunk/
WIKI:
http://code.alibabatech.com/wiki/display/FastJSON/Home
Issue Tracking:
http://code.alibabatech.com/jira/browse/FASTJSON

如果你使用了Maven,maven repository配置如下:

</pre></div></div><p style="margin-top:10px; margin-bottom:10px; padding-top:0px; padding-bottom:0px; font-family:'microsoft yahei'; font-size:15px; line-height:13pt; color:rgb(51,51,51); background-color:initial"><span style="font-size:13px">pom.xml文件中加入依赖依赖:</span></p><div class="code panel" style="font-family:'microsoft yahei'; font-size:15px; line-height:35px; padding:0px; margin:0px 0px 10px; border:1px dashed rgb(187,187,187); overflow:auto"><div class="codeContent panelContent" style="color:rgb(51,51,51); margin:0px; padding:0px 10px; background-color:initial"><pre code_snippet_id="1693889" snippet_file_name="blog_20160523_2_7453715" class="code-java" name="code" style="white-space: pre-wrap; word-wrap: break-word; padding: 0px; margin-top: 0px; margin-bottom: 0px; overflow: auto; font-family: 'Courier New', Courier, monospace; line-height: 1.3;"><dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.0.4</version>
</dependency>

如果没有使用maven,可以直接下载:

Binary : http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1.jar
Source :
http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1-sources.jar
Subversion : 
http://code.alibabatech.com/svn/fastjson/

使用介绍:
Fastjson的最主要的使用入口是com.alibaba.fastjson.JSON

<pre name="code" class="java">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。

代码示例:
代码示例用到类User和Group:

<pre name="code" class="java">public 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; }
}
public 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; }
}



Encode代码示例:

<pre name="code" class="java">import com.alibaba.fastjson.JSON;

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



Decode 代码示例:

<pre name="code" class="java">Group group2 = JSON.parseObject(jsonString, Group.class);

FastJson解析JSON步骤
 

      A、服务器端将数据转换成json字符串
           首先、服务器端项目要导入阿里巴巴的fastjson的jar包至builtPath路径下(这些可以到fastjson官网下载:http://code.alibabatech.com/wiki/display/FastJSON/Home-zh )
JSON的解析[Java-JSON、FastJSON、GSON]_第2张图片 然后将数据转为json字符串,核心函数是:
public static String createJsonString(Object value)
       {
              String alibabaJson = JSON.toJSONString(value);
              return alibabaJson;
       }
B、客户端将json字符串转换为相应的javaBean
  首先客户端也要导入fastjson的两个jar包
1、客户端获取json字符串
public class HttpUtil
{
   
    public static String getJsonContent(String urlStr)
    {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

   
    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}

2、使用泛型获取javaBean (核心函数)
        public static T getPerson(String jsonString, Class cls) {
        T t = null;
        try {
            t = JSON.parseObject(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }
public static List getPersons(String jsonString, Class cls) {
        List list = new ArrayList();
        try {
            list = JSON.parseArray(jsonString, cls);
        } catch (Exception e) {
        }
        return list;
    }
public static List> listKeyMaps(String jsonString) {
        List> list = new ArrayList>();
        try {
            list = JSON.parseObject(jsonString,
                    new TypeReference>>() {
            });

        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }


之前的一个版本是1.1.0,1.1.0采用asm和SortFastMatch算法提高性能,由于过于着急展示其优越的性能,没有进行严格测试就发布了。

1.1.1相对于1.1.0,这是一个比较稳定的版本了,行测试覆盖率重新提升到90%以上,build verify testcase 983个。

这个版本进一步完善了asm和SortFieldFastMatch算法,进一步提升了性能,同时补充了大量的testcase,提升了稳定性,我向你推荐使用这个版本,使用这个版本你将会得到令人惊奇的性能。

1.1.1版本的asm来源自objectweb的asm项目,根据fastjson的需要做裁剪,确保引入asm的同时不引起包大小的过渡变大。

为了更好使用sort field martch优化算法提升parser的性能,fastjson序列化的时候,缺省把SerializerFeature.SortField特性打开了。反序列化的时候也缺省把SortFeidFastMatch的选项打开了。这样,如果你用fastjson序列化的文本,输出的结果是按照fieldName排序输出的,parser时也能利用这个顺序进行优化读取。这种情况下,parser能够获得非常好的性能。

我使用github.com/eishay/jvm-serializers/提供的程序做测试,性能数据如下:


序列化时间 反序列化时间 大小 压缩后大小
java序列化 8546 43199 889 541
hessian 6643 10043 501 313
protobuf 3008 1694 239 149
thrift 3182 1951 349 197
avro 3575 2095 221 133
json-lib 45734 149741 485 263
jackson 3245 2986 503 271
fastjson 2292 1499 468 251

测试跑的脚本是:

<span style="font-size: 13px;">./run -chart -include=`cat serializers.txt | tr </span><span class="code-quote" style="color: rgb(0, 145, 0); background-color: inherit;"><span style="font-size: 13px;">"\\n"</span></span><span style="font-size: 13px;"> </span><span class="code-quote" style="color: rgb(0, 145, 0); background-color: inherit;"><span style="font-size: 13px;">","</span></span><span style="font-size: 13px;">`  data/media.1.cks
</span>

从上面的数据来看,fastjson的性能已经超越protobuf、thrift、avro这些二进制协议了。一个文本协议的性能超越二进制协议是很难的,我很高兴向大家宣布我做到了!!

鉴于fastjson优越的性能表现,我建议做如下事情;
1、替换其他所有的json库,java世界里没有其他的json库能够和fastjson可相比了。
2、使用fastjson的序列化和反序列化替换java serialize,java serialize不单性能慢,而且体制大。
3、使用fastjson替换hessian,json协议不必hessian体积大,而且fastjson性能优越,数倍于hessian
4、把fastjson用于memached缓存对象数据。

How to get it?

If you're Maven user, just use our maven repository(http://code.alibabatech.com/mvn/releases/) with folloging dependency

<span style="font-size: 13px;"><dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.1.1</version>
</dependency>
</span>

Downlaods

Binary : http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1.jar
Source :
http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1-sources.jar
Subversion : 
http://code.alibabatech.com/svn/fastjson/




GSON

 一、 谷歌GSON这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。


 二、Gson解析Json步骤
 A、服务器端将数据转换成json字符串
   首先、服务器端项目要导入Gson的jar包到BuiltPath中。(

Gson的jar:http://code.google.com/p/google-gson/   我们还可以下载gson的帮助文档
JSON的解析[Java-JSON、FastJSON、GSON]_第3张图片





然后将数据转为json字符串,核心函数是:
    public static String createJsonString(Object value)
    {
        Gson gson = new Gson();
        String str = gson.toJson(value);

        return str;
    }
B、客户端将json字符串转换为相应的javaBean
    首先客户端也要导入gson的两个jar包,json的jar就不需要导入了(因为android项目中已经集成了json的jar包所以这里无需导入
   1、客户端获取json字符串
public class HttpUtil
{
   
    public static String getJsonContent(String urlStr)
    {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

   
    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}

2、使用泛型获取javaBean(核心函数)
    public static <T> T getPerson(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);

        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }

public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<cls>>() {
            }.getType());

        } catch (Exception e) {
        }
        return list;
    }
public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString,
                    new TypeToken<List<Map<String, Object>>>() {
                    }.getType());

        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }

你可能感兴趣的:(JSON的解析[Java-JSON、FastJSON、GSON])