# 为了做一个数据库的的工具类,使用对象快速查询则想到了对象之间的转换,在网上查找了好多都没有自己想要的,所以就下笔自己想了一个工具类,如果此工具能帮到你我希望更好了,如果对你没有用也不要怪我,因为我也不知道你想要什么样的,就算你想要的,我也不一定写得出来哈,请大家不要见怪哈
初到而来写代码,如果问题请留言
把T对象转换为Map对象
Map对象转换为T对象
获得T对象的list中的一个
T为实体对象,没有试过其他复杂对象(对象嵌套对象可能要修改一下)
ObjectsSerializedMap < T >
在工具类里导入这个包很重要
import com.google.gson.Gson;
可以去这里查看最新的包
//http://www.mvnrepository.com/artifact/com.google.code.gson/gson
我使用的是2.8.1的包
as直接引用这个包就可以了 compile ‘com.google.code.gson:gson:2.8.1’
废话不多说了直接上代码
import com.google.gson.Gson;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by Jay on 2017/9/13 0013.
* T对象转换成amp对象
* 或者map对象转换为T对象
* <p>
* user to map or map to user
*/
public class ObjectsSerializedMap<T> {
private T object;
private Gson gson;
/**
* 把T对象转换为Map对象
*
* @param tClass T对象
* @return Map<Object,Object>
*/
public Map<Object, Object> getObjectMap(T tClass) {
try {
if (gson == null) {
gson = new Gson();
}
String jsonStr = gson.toJson(tClass);
return gson.fromJson(jsonStr, Map.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Map对象转换为T对象
*
* @param objectMap Map<Object, Object>对象
* @param object Class<T> 对象
* @return T对象
*/
public T getT(Map<Object, Object> objectMap, Class<T> object) {
try {
// //"通过Map.entrySet遍历key和value" 尤其是容量大时(相对来说 比2好一点 效率高)
// for (Map.Entry<Object, Object> entry : objectMap.entrySet()) {
// Field[] fields = object.getDeclaredFields();
// if ("$change".equals(fields[1].getName())
// || "serialVersionUID".equals(fields[1].getName())) {//这是什么鬼...不知道,应该是install run的差分编译原因
//如果想用此方法可以去自己把对象里的属性一个一个的添加
// continue;
// }
// System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
// }
if (gson == null) {
gson = new Gson();
}
String jsonStr = gson.toJson(objectMap);
return gson.fromJson(jsonStr, object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
List<T> tList = null;
/**
* 把对象转换为list对象
*
* @param tClass
* @return
*/
public List<T> setListT(T tClass) {
// try {
// if (gson==null){
// gson = new Gson();
// }
// String jsonStr = gson.toJson(tClass);//{"user":"4","ids":"3","avg":"2"}
// jsonStr="["+jsonStr+"]";
// // [{"name":"name0","age":0}]//list数据、、[{"name":"name0","age":0}][{"name":"name1","age":5}][{"name":"name2","age":10}]
// return gson.fromJson(jsonStr,new TypeToken<List<T>>(){}.getType());
// }catch (Exception e){
// e.printStackTrace();
// return null;
// }
try {
if (tList == null) {
tList = new ArrayList<T>();
}
tList.add(tClass);
return tList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获得单个T对象
* @return T 对象
*/
public T getObjectList() {
try {
if (tList != null && tList.size() > 0) {
return tList.get(0);
}
return null;
} catch (Exception e) {
return null;
}
}
}
我准备写sqlite 数据库需要的此工具,后期会有跟多更新哦,请多多支持!谢谢!**。