jsonArray转换成List

从字符串String转换成List

字符串格式:

String jsonstr = "{'studentsjson':[{'student':'张三'},{'student':'李四'}] }";

List格式:

[张三, 李四]

代码如下:

public static List StrToList1(String jsonStr) {
        List<String> list = new ArrayList<String>();
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        Iterator it = jsonObject.keys();
        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            Object obj = jsonObject.get(key);
            JSONArray jsonArr = JSONArray.fromObject(obj);
            for (Object obj2 : jsonArr) {
                Map<String, Object> map = (Map<String, Object>) obj2;
                for (Object value : map.values()) {
                    list.add(value.toString());
                }

            }
        }
        return list;
    }

main方法:

public static void main(String[] args) {
        String jsonstr = "{'studentsjson':[{'student':'张三'},{'student':'李四'}] }";
        List<String> list = StrToList1(jsonstr);
        System.out.println(list.toString());
}

注意:

要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:

  commons-beanutils-1.7.0.jar

  commons-collections-3.1.jar

  commons-lang-2.5.jar

  commons-logging.jar

  ezmorph-1.0.3.jar

  json-lib-2.4-jdk15.jar

import:

  import net.sf.json.JSONArray;

  import net.sf.json.JSONObject;

重要的一点是:

  在使用jsonArray方法时,string格式要写对,中括号一定要有。。。

posted on 2017-05-11 16:01  贝拉拉  阅读(2662)  评论(0编辑  收藏  举报

导航