注意:是否实例化Gson对象都可以实现转换的操作
Map to String
Map<String, String> data = new HashMap<>();
data.put("name", "edmond");
data.put("age", "22");
data.put("email", "bogendihong@163.com");
System.out.println(data); // {name=edmond, age=22, email=bogendihong@163.com}
String jsonStr = new Gson().toJson(data);
System.out.println(jsonStr); // {"name":"edmond","age":"22","email":"bogendihong@163.com"}
String to JsonObject
String jsonStr = "{\"name\":\"edmond\",\"age\":\"22\",\"email\":\"bogendihong@163.com\"}";
JsonObject jsonObject = new Gson().fromJson(jsonStr, JsonObject.class);
System.out.println(jsonObject); // {"name":"edmond","age":"22","email":"bogendihong@163.com"}
String to Bean类
class User {
String name;
int age;
String email;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}
String jsonStr = "{\"name\":\"edmond\",\"age\":\"22\",\"email\":\"bogendihong@163.com\"}";
User user = new Gson().fromJson(jsonStr, User.class);
System.out.println(user); // User{name='edmond', age=22, email='bogendihong@163.com'}
Map to JsonObject
Map<String, String> data = new HashMap<>();
data.put("name", "edmond");
data.put("age", "22");
data.put("email", "bogendihong@163.com");
System.out.println(data);
// 转换为String
String jsonStr = new Gson().toJson(data);
// 将String再转化为JsonObject
JsonObject jsonObject = new Gson().fromJson(jsonStr, JsonObject.class).getAsJsonObject();
System.out.println(jsonObject); // {"name":"edmond","age":"22","email":"bogendihong@163.com"}
List<Map> to JsonArray
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "John");
map1.put("age", 30);
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "Mary");
map2.put("age", 25);
list.add(map2);
String jsonStr = new Gson().toJson(list);
JsonElement element = new Gson().fromJson(jsonStr, JsonElement.class);
JsonArray jsonArray = element.getAsJsonArray();
System.out.println(jsonArray); // [{"name":"John","age":30},{"name":"Mary","age":25}]
Json数组字符串 to List
String jsonStr = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Mary\",\"age\":25}]";
JsonElement element = new Gson().fromJson(jsonStr, JsonElement.class);
JsonArray jsonArray = element.getAsJsonArray();
List<Map<String, Object>> list = new ArrayList<>();
for (JsonElement jsonElement : jsonArray) {
Map<String, Object> map = new Gson().fromJson(jsonElement, new TypeToken<Map<String, Object>>() {}.getType());
list.add(map);
}
System.out.println(list); //[{name=John, age=30.0}, {name=Mary, age=25.0}]
Bean类 to JsonObject
User user = new User("edmond", 22, "bogendihong@163.com");
JsonObject jsonObject = new Gson().toJsonTree(user).getAsJsonObject();
System.out.println(jsonObject); // {"name":"edmond","age":22,"email":"bogendihong@163.com"}