java数据类型转换____Gson框架对象和JSON转换
package com.cnse.convert.gson;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* @author Administrator
* 使用Json的开发包
*/
public class GsonUtil {
/**
* 单个对象间的转换=================================
* @param obj
* @return
*/
public static String objToJson(Object obj){
Gson g = new Gson();
return g.toJson(obj);
}
public static Object jsonToObj(Class<?> clazz, String JsonStr) throws Exception {
Gson g = new Gson();
Object obj = null;
try {
obj = g.fromJson(JsonStr, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 多个对象间的转换=====================================
* @param obj
* @return
*/
public static String objSToJson(Object obj){
Gson g = new Gson();
return g.toJson(obj);
}
public static List<User> getObjectS(String JsonStr) throws Exception {
// json转为带泛型的list
Gson g = new Gson();
List<User> retList = g.fromJson(JsonStr,new TypeToken<List<User>>() {}.getType());
return retList;
}
//==============================test
public static void main(String[] args) throws Exception {
//初始化对象
User u1 = new User();
u1.setUserid(1);
u1.setUsername("zhangsan");
u1.setPassword("123456");
User u2 = new User();
u2.setUserid(2);
u2.setUsername("lisi");
u2.setPassword("8888");
List<User>list=new ArrayList<User>();
list.add(u1);
list.add(u2);
//==========单个对象间转换
System.out.println("Gson单个对象转Json串___:"+objToJson(u1));
User us=(User) jsonToObj(User.class, objToJson(u1));
System.out.println(us.getUsername());
//=========多个对象间转换
System.out.println("Gson的list<Obj>转json串__:"+objToJson(list));
List<User>userlist =getObjectS(objToJson(list));
System.out.println("_____"+userlist.get(0).getUsername());
}
}
//User对象
package com.cnse.convert.fastjson;
/**
* @author God
* 用户对象
*/
public class User {
//general po
private int userid;
private String username;
private String password;
//encap
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
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;
}
}
//运行结果