public class JsonToJavaUtil {
/**
* 将json转成成javaBean对象
*
* @param <T>
* 返回类型
* @param json
* 字符串
* @param clazz
* 需要转换成的类
* @return
*/
public static <T> List<T> jsonToJavaBean(String json, Type type) {
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson();
list = gson.fromJson(json, type);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
-------------------
测试代码:
String str = "[{code:'0',name:'we',hsCode:'rwer',jtCode:'1',invoiceno:'r12',weight:12,capacity:45},{code:'0',name:'fgh',hsCode:'fgh',jtCode:'1',invoiceno:'dfg',weight:45,capacity:45}]";
Gson gson = new Gson();
List<TBLGoods> list = JsonToJavaUtil.jsonToJavaBean(str, new TypeToken<List<TBLGoods>>() {}.getType());
for (int i = 0; i < list.size(); i++) {
System.out.println("==================="+list.get(i).getName());
}
测试结果:
===================we
===================fgh