Java Gson 简要笔记
Gson是Google开发的Java比较好用的 Json工具。
使用挺简单,假设有个类:
1 class Runner { 2 int attr; 3 String name; 4 public Runner(int attr, String name) { 5 this.attr = attr; 6 this.name = name; 7 } 8 }
Object -> JSON (关键 line 3):
1 Gson gson = new Gson(); 2 Runner runner = new Runner(3, "lhfcws"); 3 String jsonStr = gson.toJson(runner); 4 System.out.println(jsonStr);
JSON -> Object:
1 Gson gson = new Gson(); 2 String jsonStr = "...."; 3 Runner runner = gson.fromJson(jsonStr, Runner.class);
当遇到泛型的时候,fromJson最好使用另一种方法,TypeToken。不然有时会把对象识别成LinkedHashMap结构:
1 Gson gson = new Gson(); 2 String jsonStr = "...."; 3 List<Runner> runnerList = gson.fromJson(jsonStr, new TypeToken<List<Runner>>(){}.getType());