Json数据转换
-
步骤一
- 导入jar包,地址https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.5,gson-2.8.5.jar,版本随意
-
步骤二
- 创建servlet
-
步骤三
- 实体类转json
System.out.println("=============对象转json==========="); Gson gson1 = new Gson(); User user = new User("张三","123"); String json = gson1.toJson(user); System.out.println(json);
- json转实体类
System.out.println("=============json转对象==========="); Gson gson2 = new Gson(); String gson22 = "{\"name\":\"张三\",\"pwd\":\"123\"}"; User user2 = gson2.fromJson(gson22, User.class); System.out.println(user2);
- list转json
System.out.println("=============list转json==========="); Gson gson3= new Gson(); List<User> users = new ArrayList<User>(); users.add(new User("张三","123")); users.add(new User("李四","123123")); users.add(new User("王二","123456")); users.add(new User("马子","456")); String json33 = gson3.toJson(users); System.out.println(json33);
- json转list对象
System.out.println("=============json转list对象==========="); Gson gson4 = new Gson(); String json44 = "[{\"name\":\"张三\",\"pwd\":\"123\"},{\"name\":\"李四\",\"pwd\":\"123123\"},{\"name\":\"王二\",\"pwd\":\"123456\"},{\"name\":\"马子\",\"pwd\":\"456\"}]"; List<User> user3 = gson2.fromJson(json44, new TypeToken<List<User>>(){}.getType()); for (User user4 : user3) { System.out.println(user4); }
- map转json
System.out.println("=============map转json==========="); Gson gson5= new Gson(); Map<String,Object> hashmap = new HashMap<>(); String[] str = new String[] {"basketball","rap","dance","sing"}; hashmap.put("id", "02"); hashmap.put("info", new User("张三","123")); hashmap.put("hoppy", str); String json55 = gson3.toJson(hashmap); System.out.println(json55);
- json转map对象
System.out.println("=============json转map对象==========="); Gson gson6 = new Gson(); String json66 = "{\"id\":\"02\",\"info\":{\"name\":\"张三\",\"pwd\":\"123\"},\"hoppy\":[\"basketball\",\"rap\",\"dance\",\"sing\"]}"; Map<String,Object> hashmap1 = gson6.fromJson(json66, new TypeToken<Map<String,Object>>(){}.getType()); for (String key : hashmap.keySet()) { System.out.println("key: "+key+" value:"+hashmap.get(key)); }