JAVA中json轉Map,jsonArray轉List集合,List集合轉json
阿新 • • 發佈:2019-02-14
在寫程式碼時,經常會遇到各轉型別之間互相轉換,比如json轉換為Map,jsonArray轉List集合,List集合轉json,現在整理一個工具類,方便日後查閱。
import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.zgr.pack.entity.test.TestJsonToList; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class Util { //json字串轉換為MAP public static Map jsonStrToMap(String s) { Map map = new HashMap(); //注意這裡JSONObject引入的是net.sf.json net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(s); Iterator keys = json.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = json.get(key).toString(); if (value.startsWith("{") && value.endsWith("}")) { map.put(key, jsonStrToMap(value)); } else { map.put(key, value); } } return map; } // 將jsonArray字串轉換成List集合 public static List jsonToList(String json, Class beanClass) { if (!StringUtils.isBlank(json)) { //這裡的JSONObject引入的是 com.alibaba.fastjson.JSONObject; return JSONObject.parseArray(json, beanClass); } else { return null; } } //List集合轉換為json public static JSON listToJson(List list) { JSON json=(JSON) JSON.toJSON(list); return json; } public static void main(String[] args) { System.out.println("---------------------json字串轉換為MAP---------------------"); JSONObject jsonObject=new JSONObject(); jsonObject.put("abc", 123); jsonObject.put("def", 456); System.out.println("A==========json====="+jsonObject); Map map=Util.jsonStrToMap(jsonObject.toString()); System.out.println("B==========def======"+map.get("def")); System.out.println("---------------------將jsonArray字串轉換成List集合---------------------"); String str="[{\"year\":\"2015\",\"month\":10,\"count\":47},{\"year\":2017,\"month\":12,\"count\":4}]"; //這裡需要指定泛型,我們建立一個實體類TestJsonToList List<TestJsonToList> list=Util.jsonToList(str, TestJsonToList.class); System.out.println("C==========取list第二個元素的year====="+list.get(1).getYear()); System.out.println("---------------------將list集合轉換成json---------------------"); //這裡的JSONObject引入的是 com.alibaba.fastjson.JSONObject; JSON json=Util.listToJson(list); System.out.println("D==========json====="+json); } }
實體類
public class TestJsonToList { private String year; //年 private String month; //月 private String count; //資料 public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } //構造方法 public TestJsonToList(String year, String month, String count) { this.year = year; this.month = month; this.count = count; } //預設構造方法 public TestJsonToList() { } }
控制吧輸出結果:
json轉List集合,和List集合轉json時需要注意,使用的是阿里的fastJson.jar包,不要引錯了,Maven專案對應引入:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
需要jar包,可去這裡下載: