搜索
首页
笔记
案例
关于
课程列表
JavaWeb
Tomcat安装、部署等操作
Servlet
JSP
EL表达式与JSTL标签库
文件上传与下载
cookie与session
Filter过滤器
Listener监听器
ThreadLocal
Gson
课程导航
计算机基础知识
C
Linux
linux常用软件
计算机网络
程序员修养
设计模式
工具
Git
composer
vim
IntelliJ IDEA
wireshark
laravel
Spring
SpringMVC
Maven
数据库
MySQL
Redis
MongoDB
JDBC
Mybatis
MyBatis-Plus
服务端编程
PHP
Java
shell script
JavaWeb
HTML / CSS
HTML
CSS
HTML5
CSS3
BOOTSTRAP
JavaScript
JavaScript
JQuery
layui
ThreadLocal
Gson
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。 ## 基本数据类型 ```java Gson gson = new Gson(); String s1 = gson.toJson(100); Integer o1 = gson.fromJson(s1, Integer.class); System.out.println(s1); System.out.println(o1); String s2 = gson.toJson(true); boolean o2 = gson.fromJson(s2, Boolean.class); System.out.println(s2); System.out.println(o2); String s3 = gson.toJson("Apple"); String o3 = gson.fromJson(s3, String.class); System.out.println(s3); System.out.println(o3); ``` ## 数组、POJO ```java int[] nums = {2,23,53,123}; String[] strs = {"java", "php", "c++"}; int[][] numss = { {32,124,23}, {3,21,523} }; String[][] strss = { {"php", "java", "c++"}, {"mysql", "redis", "mongodb"} }; Person person = new Person("gwx", 30, new String[]{"music", "movies", "foods"}); String s1 = gson.toJson(nums); int[] o1 = gson.fromJson(s1, int[].class); System.out.println(s1); System.out.println(Arrays.toString(o1)); String s2 = gson.toJson(strs); String[] o2 = gson.fromJson(s2, String[].class); System.out.println(s2); System.out.println(Arrays.toString(o2)); String s3 = gson.toJson(numss); int[][] o3 = gson.fromJson(s3, int[][].class); System.out.println(s3); System.out.println(Arrays.deepToString(o3)); String s4 = gson.toJson(strss); String[][] o4 = gson.fromJson(s4, String[][].class); System.out.println(s4); System.out.println(Arrays.deepToString(o4)); String s5 = gson.toJson(person); Person o5 = gson.fromJson(s5, Person.class); System.out.println(s5); System.out.println(o5); ``` ## List ```java ArrayList
people = new ArrayList<>(); people.add(new Person("james", 36, new String[]{"basketball", "movie"})); people.add(new Person("gwx", 30, new String[]{"basketball", "music"})); String s = gson.toJson(people); ArrayList
o = gson.fromJson(s, new TypeToken
>(){}.getType()); System.out.println(s); System.out.println(o.get(0)); ``` ## Map ```java HashMap
map = new HashMap<>(); map.put("james", new Person("james", 36, new String[]{"basketball", "movie"})); map.put("gwx", new Person("gwx", 30, new String[]{"basketball", "music"})); String s = gson.toJson(map); HashMap
o = gson.fromJson(s, new TypeToken
>(){}.getType()); System.out.println(s); System.out.println(o.get("james")); ```
ThreadLocal
文章目录