1 package tools; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 8 import net.sf.json.JSONArray; 10 import com.alibaba.fastjson.JSONObject; 11 import com.google.gson.Gson; 12 import com.fasterxml.jackson.core.JsonProcessingException; 13 import com.fasterxml.jackson.core.type.TypeReference; 14 import com.fasterxml.jackson.databind.ObjectMapper; 16 import bean.Student; 17 18 public class Json { 19 public static void main(String[] args) { 20 //json对象转json字符串 21 jsonObjToJsonStr(); 22 //json字符串转json对象 23 jsonStrToJsonObj(); 24 //list转json 25 listToJson(); 26 //json转list 27 jsonToList(); 28 //json转map 29 jsonToMap(); 30 //map转json 31 mapToJson(); 32 } 33 34 /** 35 * map转json 36 */ 37 private static void mapToJson() { 38 ObjectMapper mapper = new ObjectMapper(); 39 String json = ""; 40 Map<String, String> map = new HashMap<String,String>(); 41 map.put("name", "JSON"); 42 map.put("age", "23"); 43 map.put("address", "北京市西城区"); 44 try { 45 json = mapper.writeValueAsString(map); 46 } catch (JsonProcessingException e) { 47 e.printStackTrace(); 48 } 49 System.out.println(json); 50 } 51 52 /** 53 * json转map 54 */ 55 private static void jsonToMap() { 56 String json = "{\"name\":\"JSON\",\"address\":\"北京市西城区\",\"age\":23}"; 57 Map<String, String> map = new HashMap<String, String>(); 58 ObjectMapper mapper = new ObjectMapper(); 59 try{ 60 map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}); 61 System.out.println(map); 62 }catch(Exception e){ 63 e.printStackTrace(); 64 } 65 } 66 67 /** 68 * json转list 69 */ 70 private static void jsonToList() { 71 //json转成list 72 String json ="[\"abc\",\"123\"]"; 73 JSONArray jsonArray = JSONArray.fromObject(json); 74 List<String> list = (List) JSONArray.toCollection(jsonArray); 75 for (int i = 0; i < list.size(); i++) { 76 System.out.println(list.get(i)); 77 } 78 } 79 80 /** 81 * list转json 82 */ 83 private static void listToJson() { 84 List<String> list = new ArrayList<String>(); 85 list.add("abc"); 86 list.add("123"); 87 //list转成json 88 String json =JSONArray.fromObject(list).toString(); 89 System.out.println(json); 90 //运行:["abc","123"] 91 } 92 93 /** 94 * json字符串转json对象 95 */ 96 private static void jsonStrToJsonObj() { 97 //json转为json对象,取属性值 98 String json ="{\"name\":\"JSON\",\"address\":\"北京市西城区\",\"age\":23}"; 99 JSONObject jo = (JSONObject) JSONObject.parse(json); 100 String add = jo.getString("address"); 101 System.out.println(add); 102 } 103 104 /** 105 * json对象转json字符串 106 */ 107 private static void jsonObjToJsonStr() { 108 Student stu=new Student(); 109 stu.setName("JSON"); 110 stu.setAge(23); 111 stu.setAddress("北京市西城区"); 112 //对象转换为json字符串 113 Gson gson = new Gson(); 114 String json = gson.toJson(stu); 115 System.out.println(json); 116 } 117 }