Gson
Gson 是一个 Google 提供的一个 Java 库,可用于将 Java 对象转换为 JSON 表示。它也可以被用来
将 JSON 字符串转换成一个等效的 Java 对象。
对象与Json的转换
public class JsonServlet01 extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("=====对象转json");
//创建对象
User user = new User("doinb","韩国",true);
//创建Gson对象
Gson gson = new Gson();
//对象转json
String json = gson.toJson(user);
//打印json对象
System.out.println(json);//{"name":"doinb","address":"韩国","sex":true}
System.out.println("=====json转对象");
//创建json对象
String json1 = "{\"name\":\"doinb\",\"address\":\"韩国\",\"sex\":true}";
//创建Gson对象
Gson gson1 = new Gson();
//json转对象
User user2 = gson1.fromJson(json1, User.class);
//打印User对象
System.out.println(user2);//User [name=doinb, address=韩国, sex=true]
}
}
List与Json的转换
public class JsonServlet02 extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("=====List转Json");
//创建List对象
List<User> list = new ArrayList<User>();
list.add(new User("UZI","China",true));
list.add(new User("MLXG","China",true));
list.add(new User("doinb","韩国",true));
//创建Gson对象
Gson gson = new Gson();
//List转Json
String json = gson.toJson(list);
//打印
System.out.println(json);
/*
* [{"name":"UZI","address":"China","sex":true},
* {"name":"MLXG","address":"China","sex":true},
* {"name":"doinb","address":"韩国","sex":true}]
*/
System.out.println("=====Json转List");
//创建Json对象
String json1 = "[{\"name\":\"UZI\",\"address\":\"China\",\"sex\":true},"
+ "{\"name\":\"MLXG\",\"address\":\"China\",\"sex\":true},"
+ "{\"name\":\"doinb\",\"address\":\"韩国\",\"sex\":true}]";
//创建Gson对象
Gson gson1 = new Gson();
//Json转List
List<User> list1 = gson1.fromJson(json1, new TypeToken<List<User>>(){}.getType());
//打印
for (User u : list1) {
System.out.println(u);
}
/*
* User [name=UZI, address=China, sex=true]
User [name=MLXG, address=China, sex=true]
User [name=doinb, address=韩国, sex=true]
*/
}
}
Map与Json的转换
public class JsonServlet03 extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("=====Map转Json=====");
//创建Map对象
Map<String,Object> map = new HashMap<>();
map.put("id", "001");
map.put("user", new User("doinb","韩国",true));
//创建Gson对象
Gson gson = new Gson();
//Map转Json
String json = gson.toJson(map);
//打印
System.out.println(json);
//{"id":"001","user":{"name":"doinb","address":"韩国","sex":true}}
System.out.println("=====Json转Map");
//创建Json对象
String json01 = "{\"id\":\"001\",\"user\":{\"name\":\"doinb\",\"address\":\"韩国\",\"sex\":true}}";
//创建Gson对象
Gson gson1 = new Gson();
//Json转map
Map<String,Object> map1 = gson1.fromJson(json01, new TypeToken<Map<String,Object>>(){}.getType());
//打印
for(String key : map1.keySet()) {
System.out.println(key+":"+map1.get(key));
}
//id:001
//user:{name=doinb, address=韩国, sex=true}
}
}