首頁 > 軟體

Java中如何將json字串轉換成map/list

2022-07-06 14:04:38

將json字串轉換成map/list

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
 
public class JsonStr2MapOrList {
 
    /**
     * 以"{"開頭的jsonStr轉map,map裡面有list,list裡面還裝有map
     */
    @SuppressWarnings("rawtypes")
    public static Map<String, Object> jsonStr2Map(String jsonStr) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!jsonStr.isEmpty()) {
            JSONObject json = new JSONObject(jsonStr);
            Iterator i = json.keys();
            while (i.hasNext()) {
                String key = (String) i.next();
                String value = json.getString(key);
                if (value.indexOf("{") == 0) {
                    map.put(key.trim(), jsonStr2Map(value));
                } else if (value.indexOf("[") == 0) {
                    map.put(key.trim(), jsonStr2List(value));
                } else {
                    map.put(key.trim(), value.trim());
                }
            }
        }
        return map;
    }
 
    /**
     * 以"["開頭的String轉list,list裡裝有map
     */
    public static List<Map<String, Object>> jsonStr2List(String jsonStr) throws Exception {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        JSONArray ja = new JSONArray(jsonStr);
        for (int j = 0; j < ja.length(); j++) {
            String jm = ja.getString(j);
            if (jm.indexOf("{") == 0) {
                Map<String, Object> m = jsonStr2Map(jm);
                list.add(m);
            }
        }
        return list;
    }
 
    /**
     * jsonStr和Map之間的轉換, jsonStr和List之間的轉換
     * 
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 1.jsonStr和Map之間的轉換
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("key1", "val1");
        map.put("key2", "val2");
 
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        Map<String, Object> map2 = new HashMap<String, Object>();
        map1.put("key11", "val11");
        map1.put("key21", "val21");
        map2.put("key111", "val111");
        map2.put("key211", "val211");
        list.add(map1);
        list.add(map2);
        map.put("keyList", list);
 
        System.out.println("原始的map:" + map);
        String map2JsonStr = map.toString();
        System.out.println("map2JsonStr:" + map2JsonStr);
        Map<String, Object> jsonStr2Map = jsonStr2Map(map2JsonStr);
        System.out.println("jsonStr2Map:" + jsonStr2Map);
 
        // 2.jsonStr和List之間的轉換
        List<Object> list_ = new ArrayList<Object>();
        list_.add(map);
        String list_Str = list_.toString();
        System.out.println("list_Str:" + list_Str);
        List<Map<String, Object>> listM = jsonStr2List(list_Str);
        System.out.println("listM:" + listM);
    }
}

輸出結果:

原始的map:{key2=val2, key1=val1, keyList=[{key11=val11, key21=val21}, {key211=val211, key111=val111}]}
map2JsonStr:{key2=val2, key1=val1, keyList=[{key11=val11, key21=val21}, {key211=val211, key111=val111}]}
jsonStr2Map:{key2=val2, key1=val1, keyList=[{key11=val11, key21=val21}, {key211=val211, key111=val111}]}
list_Str:[{key2=val2, key1=val1, keyList=[{key11=val11, key21=val21}, {key211=val211, key111=val111}]}]
listM:[{key2=val2, key1=val1, keyList=[{key11=val11, key21=val21}, {key211=val211, key111=val111}]}]

字串,json,Map互相轉換(各種轉換都有)

前提:使用jar包為fastjson

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

程式如下

        Map map = new HashMap();
        map.put("AAA", "1");
        map.put("BBB", "2");
        map.put("CCC", "3");
        System.out.println("map=>"+map);
        
        //1.map轉string
        String jsonString = JSON.toJSONString(map);
        System.out.println("mapToString=>"+jsonString);
        //2.map轉jsonObject 
        JSONObject JSONObj = JSONObject.parseObject(JSON.toJSONString(map));
        System.out.println("mapToJSON=>"+JSONObj);
        
        //3.String轉jsonObject
        String jsonString2 = "{"AAA":"1","CCC":"3","BBB":"2"}";
        JSONObject parseObject = JSONObject.parseObject(jsonString2);
        System.out.println("StringToJson=>"+parseObject);
        //4.String轉map
        Map stringToMap =  JSONObject.parseObject(jsonString2); 
        System.out.println("StringToMap=>"+stringToMap);
        
        String str = "{"age":"24","name":"summer"}";
        JSONObject  jsonObject = JSONObject.parseObject(str);
        //5.jsonObject轉map
        Map jsonToMap =  JSONObject.parseObject(jsonObject.toJSONString()); 
        System.out.println("jsonToMap=>"+jsonToMap);
        //6.jsonObject轉String
        String jsonString3 = jsonObject.toJSONString();
        System.out.println("jsonToString=>"+jsonString3);

結果如下

map=>{AAA=1, CCC=3, BBB=2}
mapToString=>{"AAA":"1","CCC":"3","BBB":"2"}
mapToJSON=>{"AAA":"1","CCC":"3","BBB":"2"}
StringToJson=>{"AAA":"1","CCC":"3","BBB":"2"}
StringToMap=>{"AAA":"1","CCC":"3","BBB":"2"}
jsonToMap=>{"name":"summer","age":"24"}
jsonToString=>{"name":"summer","age":"24"}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com