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处理的方法都可以找到对应的类;贴上一段代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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集合,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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集合,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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

java中Array/List/Map/Object与Json互相转换详解(转载)的更多相关文章

  1. java中Array/List/Map/Object与Json互相转换详解

    http://blog.csdn.net/xiaomu709421487/article/details/51456705 JSON(JavaScript Object Notation): 是一种轻 ...

  2. JAVA中list,set,map与数组之间的转换详解

    package test; import java.util.*; /** * Created by ming */ public class Test { public static void ma ...

  3. JAVA中时间格式(SimpleDateFormat)和数字格式(DecimalFormat)转换详解(转)

    时间格式转换SimpleDateFormat: //定义日期的格式 SimpleDateFormat format =new SimpleDateFormat("yyMMdd"); ...

  4. PHP中IP地址与整型数字互相转换详解

    这篇文章主要介绍了PHP中IP地址与整型数字互相转换详解,本文介绍了使用PHP函数ip2long与long2ip的使用,以及它们的BUG介绍,最后给出自己写的两个算法,需要的朋友可以参考下 IP转换成 ...

  5. Java中数组判断元素存在几种方式比较详解

    1. 通过将数组转换成List,然后使用List中的contains进行判断其是否存在 public static boolean useList(String[] arr,String contai ...

  6. java中String类、StringBuilder类和StringBuffer类详解

    本位转载自http://www.cnblogs.com/dolphin0520/p/3778589.html  版权声明如下: 作者:海子 出处:http://www.cnblogs.com/dolp ...

  7. Java中的公平锁和非公平锁实现详解

    前言 Java语言中有许多原生线程安全的数据结构,比如ArrayBlockingQueue.CopyOnWriteArrayList.LinkedBlockingQueue,它们线程安全的实现方式并非 ...

  8. java中装箱和拆箱的详细使用(详解)

    一.什么是装箱?什么是拆箱? 在前面的文章中提到,Java为每种基本数据类型都提供了对应的包装器类型,至于为什么会为每种基本数据类型提供包装器类型在此不进行阐述,有兴趣的朋友可以查阅相关资料.在Jav ...

  9. Java中通过Class类获取Class对象的方法详解

    方式1:通过Object类的getObject()方法 Person p = new Person(); Class c = p.getClass(); 方式2: 通过 类名.class 获取到字节码 ...

随机推荐

  1. gen_grant_sel.sql

    set echo off feedback off verify off pagesize 0 linesize 120 define v_grantee=&1 define v_grant_ ...

  2. Ubuntu下安装Hudson

    因为hudson需要依赖java等,手动安装比较费劲 官方给出了一种很简单的解决方案:http://wiki.eclipse.org/Hudson-ci/Installing_Hudson_DEB 1 ...

  3. C# dev gridcontrol中添加checkbox复选框

    文章来源 csdn weinierbian http://blog.csdn.net/weinierbian/article/details/6255402 添加一列,FieldName为 " ...

  4. javascript类的继承

    1.构造函数方式写类,通过方法调用复制父类属性/字段到子类 实现继承 这里父类,子类都采用构造函数方式写,不用原型.子类调用父类函数来复制父类的属性. 1 2 3 4 5 6 7 8 9 10 11 ...

  5. JavaFX 2.0+ WebView /WebEngine render web page to an image

    http://stackoverflow.com/questions/7796558/javafx-2-0-webview-webengine-render-web-page-to-an-image ...

  6. Android5.1图库Gallery2代码分析数据加载流程

    图片数据加载流程. Gallery---->GalleryActivity------>AlbumSetPage------->AlbumPage--------->Photo ...

  7. 【翻译】go语言中的map实战

    业余时间翻译,水平很差,如有瑕疵,纯属无能. 原文链接 http://blog.golang.org/go-maps-in-action go语言中的map实战 1. 简介 哈希表是计算机科学中最重要 ...

  8. Linux安装php的Redis扩展

    1.安装redis 下载:https://github.com/nicolasff/phpredis/archive/2.2.4.tar.gz 上传phpredis-2.2.4.tar.gz到/usr ...

  9. URL与String转换

    NSString *str = @"www.baidu.com"; NSURL *URL = [NSURL URLWithString:str];  //string>url ...

  10. iOS给model排序

    今天有朋友问我怎么给Model排序,我顺便写了一个例子, 以下是代码,很简洁可以直接用. Person *per = [[Person alloc] init]; per.name = @" ...