/** * 测试所使用到的对象 */ class User{ private String userName; private String passWord; public User(String userName, String passWord) { this.userName = userName; this.passWord = passWord; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return "账号为:" + this.userName + " 密码为:" + this.passWord; } }
/** *对象转Json格式字符串: */ public static String toJson(Object obj) { return new Gson().toJson(obj); } User user = new User("张三", "123456"); System.out.println(JsonUtil.toJson(user)); 运行结果:
{"userName":"张三","passWord":"123456"}
/** * Json格式字符串转单个对象 */ public static <T> T fromJson(String jsonStr, Type type) { return new Gson().fromJson(jsonStr, type); } String Json = "{\"userName\":\"张三\",\"passWord\":\"123456\"}"; User user = JsonUtil.fromJson(Json, User.class)System.out.println(user); 运行结果:
账号为:张三 密码为:123456
/** *如果是多个对象组成的Josn格式字符串 */ public static <T> List<T> jsonToList(String jsonStr, Class<T[]> type) { T[] list = new Gson().fromJson(jsonStr,type); return Arrays.asList(list); } List<User> list = new ArrayList<User>(); list.add(new User("张三", "123456")); list.add(new User("李四", "000000")); String json = JsonUtil.toJson(list); list = JsonUtil.jsonToList(json, User[].class); System.out.println(list.get(1)); 运行结果:
账号为:李四 密码为:000000
时间: 2024-11-10 08:03:06