package json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonDemo {
private static Gson gson = new Gson();
//对象转Json
public static String ClassToJson() {
User user = new User();
user.setId("1");
user.setName("王二麻子");
String json = gson.toJson(user);
return json;
}
//Json转对象
public static User JsonToClass() {
String classJson = ClassToJson();
User user = gson.fromJson(classJson, User.class);
return user;
}
//List集合转Json数组
public static String ListToJson() {
List<User> userList = new ArrayList<>();
userList.add(new User("1","王一麻子"));
userList.add(new User("2","王二麻子"));
userList.add(new User("3","王三麻子"));
userList.add(new User("4","王四麻子"));
userList.add(new User("5","王五麻子"));
userList.add(new User("6","王六麻子"));
String json = gson.toJson(userList);
return json;
}
//Json转List集合
public static List<User> JsonToList(){
String listJson = ListToJson();
List<User> jsonList = gson.fromJson(listJson, new TypeToken<List<User>>() {}.getType());
return jsonList;
}
//Map转Json
public static String MapToJson() {
Map<String,User> map = new HashMap<>();
map.put("大哥", new User("1","李狗蛋子"));
map.put("二哥", new User("2","李猫蛋子"));
map.put("三哥", new User("3","李竹鼠蛋子"));
String json = gson.toJson(map);
return json;
}
//Json转Map
public static Map JsonToMap() {
String mapJson = MapToJson();
Map<String,User> jsonMap = gson.fromJson(mapJson, Map.class);
return jsonMap;
}
public static void main(String[] args) {
System.out.println(ClassToJson());//对象转Json
System.out.println(JsonToClass());//Json转对象
System.out.println(ListToJson());//List集合转Json数组
JsonToList().forEach(x->System.out.println(x));//Json转List集合
System.out.println(MapToJson());//Map转Json
JsonToMap().forEach((x,y) -> {System.out.println(x+":"+y);});//Json转Map
}
}