Fork me on GitHub

Json字符串转换为java对象的各种实现方法【json_lib框架、Gson、org.json】

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://mengzhengbin520.blog.51cto.com/7590564/1283361

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。

   欲实现JSON字符串和java对象之间的互相转换,方法有很多!本人层也因为项目上的需求,一度对这几种方法做过研究和试验!现将自己的一点小经验分享与大家,如有纰漏,请指正!

   1.通过json_lib来实现对json和java对象之间的转换,使用JSON-LIB可以极大的简化JAVA对象转换成JSON对象所需进行的操作,更可以避免人工操作生成JSON对象字符串时带来的麻烦和误操作:

   注:欲使用json_lib需要以下几个jar包的支持:

json-lib-1.1-jdk15.jar  下载地址:http://json-lib.sourceforge.net

       commons-collections-3.2.1.jar

       commons-lang-2.4.jar

       commons-logging-1.1.1.jar

       commons-beanutils-1.8.0.jar

       以上commons系列包在tomcat/comon/lib下可以找到;

       ezmorph-1.0.6.jar    下载地址http://ezmorph.sourceforge.net

       morph-1.0.1 下载地址:http://morph.sourceforge.net

   有了这些jar包的支持,平时关于json处理的方法都可以找到对应的类;贴上一段代码示例:


package util;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

public class JSONHelper {

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

     /**

      * 将JSONArray对象转换成Map-List集合

      * @param jsonArr

      * @return

      */

     public static Object JsonToList(JSONArray jsonArr){

         List<Object> jsonObjList = new ArrayList<Object> ();

         for(Object obj : jsonArr){

             if(obj instanceof JSONArray){

                 jsonObjList.add(JsonToList((JSONArray) obj));

             } else if(obj instanceof JSONObject){

                 jsonObjList.add(JsonToMap((JSONObject) obj));

             }else{

                 jsonObjList.add(obj);

             }

         }

         return jsonObjList;

     }

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    /**

     *  将JSONObjec对象转换成Map-List集合

     * @param json

     * @return

     */

     public static Map<String, Object> JsonToMap(JSONObject json){

         Map<String,Object> columnValMap = new HashMap<String,Object>();

         Set<Object> jsonKeys = json.keySet();

         for (Object key : jsonKeys) {

             Object JsonValObj = json.get(key);

             if(JsonValObj instanceof JSONArray){

                columnValMap.put((String)key,  JsonToList((JSONArray) JsonValObj));

             }else if(key instanceof JSONObject){

                columnValMap.put((String)key,  JsonToMap((JSONObject) JsonValObj));

             }else{

                 columnValMap.put((String)key,JsonValObj);

             }

        }

         return columnValMap;

     }

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

     /**

      * 将json对象转换为map集合,通过此方法获取存放map集合键的list集合

      * @param obj

      * @return

      */

     public static List<Object> mapKeys(Object obj){

         List<Object> keysList = new ArrayList<Object>();

         Map<String,Object> columnValMap = new HashMap<String,Object>();

         String columnStr = "column";

         if(obj instanceof JSONArray){

             List<Map<String, Object>> jsonObjList = new ArrayList<Map<String, Object>> ();

             jsonObjList = (List<Map<String, Object>>) JsonToList((JSONArray) obj);

             columnValMap =(Map<String, Object>) (jsonObjList.get(0));

             //以上三句可优化为如下一句

             //columnValMap =(Map<String, Object>)(((List<Object>)JsonToList((JSONArray) obj)).get(0));

         }else if(obj instanceof JSONObject){

             columnValMap =JsonToMap((JSONObject) obj);

         }else{

             keysList.add(obj);

         }

         for(int i=0;i<columnValMap.keySet().size();i++){

             keysList.add(columnStr+(i+1));

         }

         System.out.println(keysList.size());

         return keysList;

     }

}

     2.通过使用谷歌的Gson来处理json字符串,谷歌的Gson针对封装的javaBean处理起来很方便,但对于未封装的json字符串需要找到技巧处理起来也才能顺手。

      使用谷歌的Gson当然也需要jar包的支持,这需要一个jar包:Gson.jar

      下载地址:http://code.google.com/p/google-gson/downloads/detail?name=google-gson-2.2.4-release.zip

       示例:将通过js获取的json字符串转换为Map、List集合,代码如下:


package util;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import com.google.gson.Gson;

public class JSONHelper {

    private Gson gson = new Gson();

                                                                                                                                                                                                                                                                                                                                                                                                                                                 

    /**

      * 将json对象转换为map集合,通过此方法获取存放map集合键的list集合

      * @param obj

      * @return

      */

    public static List<Object> mapKeys(Map<?,?> map){

         List<Object> keysList = new ArrayList<Object>();

         String columnStr="column";

         for(int i=0;i<map.keySet().size();i++){

             keysList.add(columnStr+(i+1));

         }

         System.out.println(keysList.size());

         return keysList;

    }

                                                                                                                                                                                                                                                                                                                                                                                                                                                 

                                                                                                                                                                                                                                                                                                                                                                                                                                                 

    /**

     * 将传入的json字符串转换为元素为map集合的List集合

     * @param jsonArrStr

     * @return

     */

    public static List<Map<String, Object>> jsonObjList(String jsonArrStr) {

        List<Map<String, Object>> jsonObjList = new ArrayList<Map<String, Object>>();

        List<?> jsonList = Test.jsonToList(jsonArrStr);

        Gson gson = new Gson();

        for (Object object : jsonList) {

            String jsonStr = gson.toJson(object);

            Map<?, ?> json = Test.jsonToMap(jsonStr);

            jsonObjList.add((Map<String, Object>) json);

        }

        return jsonObjList;

    }

                                                                                                                                                                                                                                                                                                                                                                                                                                                 

                                                                                                                                                                                                                                                                                                                                                                                                                                                 

    /**

     * 将传入的json字符串解析为List集合

     * @param jsonStr

     * @return

     */

    public static List<?> jsonToList(String jsonStr) {

        List<?> ObjectList = null;

        Gson gson = new Gson();

        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<?>>() {}.getType();

        ObjectList = gson.fromJson(jsonStr, type);

        return ObjectList;

    }

                                                                                                                                                                                                                                                                                                                                                                                                                                                 

    /**

     * 将传入的json字符串解析为Map集合

     * @param jsonStr

     * @return

     */

    public static Map<?, ?> jsonToMap(String jsonStr) {

        Map<?, ?> ObjectMap = null;

        Gson gson = new Gson();

        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?,?>>() {}.getType();

        ObjectMap = gson.fromJson(jsonStr, type);

        return ObjectMap;

    }

}

    3.使用最轻量级的org.json.jar实现json字符串和java对象之间的互转

       所需jar包:org.json.jar

       下载地址:www.json.org  或第三方:http://kiccp.sinaapp.com/store/info/111

       同样实现对json字符串转换为Map、List集合,代码如下:


package util;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

/**

 * 此类是处理json字符串的工具类

 *

 * @author xiaomeng

 * @since 2013-08-27

 *

 */

public class JSONHelper {

    /**

     * 将json字符串转换为List集合

     *

     * @param jsonArrStr

     * @return

     */

    public static List<Map<String, Object>> jsonObjList(String jsonArrStr) {

        List<Map<String, Object>> jsonList = new ArrayList<Map<String, Object>>();

        JSONArray jsonArr = null;

        try {

            jsonArr = new JSONArray(jsonArrStr);

            jsonList = (List<Map<String, Object>>)JSONHelper.jsonToList(jsonArr);

        } catch (JSONException e) {

            System.out.println("Json字符串转换异常!");

            e.printStackTrace();

        }

        return jsonList;

    }

    /**

     * 将json对象的键值存放在集合,映射table的column

     *

     * @param map

     * @return

     */

    public static List<String> jsonMapKeysList(Map<?, ?> map) {

        List<String> jsonjsonList = new ArrayList<String>();

        String columnStr = "column";

        for (int i = 0; i < map.keySet().size(); i++) {

            jsonjsonList.add(columnStr + (i + 1));

        }

        System.out.println(jsonjsonList.size());

        return jsonjsonList;

    }

    /**

     * 将传递近来的json数组转换为List集合

     *

     * @param jsonArr

     * @return

     * @throws JSONException

     */

    private static List<?> jsonToList(JSONArray jsonArr)

            throws JSONException {

        List<Object> jsonToMapList = new ArrayList<Object>();

        for (int i = 0; i < jsonArr.length(); i++) {

            Object object = jsonArr.get(i);

            if (object instanceof JSONArray) {

                jsonToMapList.add(JSONHelper.jsonToList((JSONArray) object));

            } else if (object instanceof JSONObject) {

                jsonToMapList.add(JSONHelper.jsonToMap((JSONObject) object));

            } else {

                jsonToMapList.add(object);

            }

        }

        return jsonToMapList;

    }

    /**

     * 将传递近来的json对象转换为Map集合

     *

     * @param jsonObj

     * @return

     * @throws JSONException

     */

    @SuppressWarnings("unchecked")

    private static Map<String, Object> jsonToMap(JSONObject jsonObj)

            throws JSONException {

        Map<String, Object> jsonMap = new HashMap<String, Object>();

        Iterator<String> jsonKeys = jsonObj.keys();

        while (jsonKeys.hasNext()) {

            String jsonKey = jsonKeys.next();

            Object jsonValObj = jsonObj.get(jsonKey);

            if (jsonValObj instanceof JSONArray) {

                jsonMap.put(jsonKey, JSONHelper.jsonToList((JSONArray) jsonValObj));

            } else if (jsonValObj instanceof JSONObject) {

                jsonMap.put(jsonKey, JSONHelper.jsonToMap((JSONObject) jsonValObj));

            } else {

                jsonMap.put(jsonKey, jsonValObj);

            }

        }

        return jsonMap;

    }

}

以上三种常用的json和java对象之间的互相转换方法各有其特点,根据我的小经验,现将其优缺点总如下,供参考!

    1.json_lib json解析框架

       优点:各种复杂json格式和对json处理的一般需求都可以做到

       缺点:所需支持的jar文件较多,并且关于jar包版本或许会出现一些杂七杂八的问题

    2.谷歌Gson对json的解析:

       优点:(1)。可以谷歌的Gson就是为处理java对象和json之间转换开发的框架,其可以很简单、方便的对封装的java对象和json格式文本之间的转换,包括java工具类集合之间的转换也很方便;(2)。相对json_lib框架来说,只需要一个Gson.jar就可以,需要jar文件数量少;

       缺点:由于其相对来说偏向于处理java对象和json之间的转换,所以其只简单的处理json字符串和集合类之间的转换稍微需要一个过渡,就是使用反射确定转换的java对象类型。

     3.org.json框架

       优点:在这三者之中,其实最轻量级、同谷歌Gson一样所需jar文件也是最少的一种方法,并且其在处理json字符串到java集合的转黄相对简便

缺点:相对Gson处理java对象和json之间的转换比较费事

综述:这三种解析json的方法各有优缺点,具体可根据自己需求选择使用。

本文出自 “有梦就有希望” 博客,请务必保留此出处http://mengzhengbin520.blog.51cto.com/7590564/1283361

附件下载:
  json-lib-2.4-jdk15框架jar包及其附属jar包
  google-gson最新版本jar包
  org.json.jar包

posted @ 2013-12-09 22:54  _落雨  阅读(623)  评论(0编辑  收藏  举报