public static void main(String[] args) {
// 序列化 把JavaBean对象转成JSON格式的字符串
// 一、基本的序列化
String objJson = JSON.toJSONString(Object object);
// 1、将Map转成JSON
Map<String, Object> map = new HashMap<String, Object>();
map.put("key1", "One");
map.put("key2", "Two");
String mapJson = JSON.toJSONString(map);
// {"key1":"One","key2":"Two"}
// 2、自定义JavaBean User转成JSON
User user = new User();
user.setUserName("张三");
user.setAge(20);
String userJson = JSON.toJSONString(user);
// {"age":20,"userName":"张三"}
// 反序列化 把JSON格式的字符串转化为Java Bean对象
// 泛型的反序列化,使用 TypeReference 传入类型信息
Map<String, Object> map1 = JSON.parseObject(mapJson, new TypeReference<Map<String, Object>>() {
});
System.out.println(map1.get("key1"));
System.out.println(map1.get("key2"));
// One
// Two
// 指定Class信息反序列化
User user1 = JSON.parseObject(userJson, User.class);
System.out.println(user1.getUserName());
// 张三
//JSONObject,JSONArray
//JSONObject,JSONArray是JSON的两个子类。
//JSONObject相当于 Map<String, Object>
//JSONArray相当于 List
//将Map转成JSONObject,然后添加元素,输出
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("key1", "One");
map2.put("key2", "Two");
JSONObject j = new JSONObject(map2);
j.put("key3", "Three");
System.out.println(j.get("key1"));
System.out.println(j.get("key2"));
System.out.println(j.get("key3"));
}
Java中字符串String格式转化成json格式【com.alibaba.fastjson.JSON】
最新推荐文章于 2024-03-20 00:14:13 发布