Java对象转JSON字符串/JSON对象:
Map
private static void map2JSON(){Map<String,Object> map = new HashMap<>();map.put("id",1);map.put("name","张三");map.put("birthday",new Date());String jsonString = JSON.toJSONString(map);JSONObject jsonObject = (JSONObject) JSON.toJSON(map);System.out.println(jsonString);System.out.println(jsonObject);
}
List
private static void list2JSON(){List<String> list = new ArrayList<>();list.add("a");list.add("b");list.add("c");String jsonString = JSON.toJSONString(list);JSONArray jSONArray = (JSONArray) JSONArray.toJSON(list);System.out.println(jsonString);System.out.println(jSONArray);
}
JavaBean
private static void bean2JSON(){Person p = new Person(1,"张三",new Date());String jsonString = JSON.toJSONString(p);JSONObject jsonObject = (JSONObject) JSON.toJSON(p);System.out.println(jsonString);System.out.println(jsonObject);
}
JSON字符串/JSON对象转Java对象:
Map
private static void JSON2Map(){JSONObject jsonObject = new JSONObject();jsonObject.put("a",1);jsonObject.put("b","bb");jsonObject.put("c",new Date());String jsonString = jsonObject.toJSONString();Map<String,Object> map1 = JSON.parseObject(jsonString, Map.class);System.out.println(map1);
}
List
private static void JSON2Array(){JSONArray jsonArray = new JSONArray();jsonArray.add("a");jsonArray.add("b");jsonArray.add("c");jsonArray.add("d");String jsonString = jsonArray.toJSONString();List<String> list = JSONArray.parseArray(jsonString, String.class);System.out.println(list);
}
JavaBean
private static void JSON2Person(){JSONObject jsonObject = new JSONObject();jsonObject.put("id",1);jsonObject.put("name","张三");jsonObject.put("birthday",new Date());String jsonString = jsonObject.toJSONString();System.out.println(jsonString);Person person = JSONObject.parseObject(jsonString, Person.class);System.out.println(person);
}
复杂数据类型
private static void JSON2ListInMap(){// 创建一个map对象,模拟前台请求返回的数据Map<String,Object> result = new HashMap<>();result.put("status","success");result.put("code","200");List<Person> list = new ArrayList<>();list.add(new Person(1,"张三",new Date()));list.add(new Person(2,"李四",new Date()));list.add(new Person(3,"王五",new Date()));list.add(new Person(4,"赵六",new Date()));result.put("data",list);// 将map对象转换成JSON字符串String jsonString = JSON.toJSONString(result);System.out.println(jsonString);// 对JSON字符串进行解析,获取Map对象// 直接转换的话,data内的集合为JSONArray,集合内存储的为JSONObjectMap<String,Object> map = JSONObject.parseObject(jsonString, Map.class);System.out.println(map);// 先把JSON字符串转换成JsonObjectJSONObject jsonObject = (JSONObject)JSONObject.parse(jsonString);// 获取JSONArray对象JSONArray jsonArray = (JSONArray) jsonObject.get("data");// 解析JSONArray对象获取Person集合List<Person> array = JSONArray.parseArray(jsonArray.toJSONString(), Person.class);// 重新赋值到mapmap.put("data",array);System.out.println(map);
}