您的位置:首页 > 编程语言 > Java开发

json转成java对象

2015-08-18 11:24 435 查看
avro生成的代码里,String是CharSequence,不能通过Gson反序列化,于是有了下面的代码,ParseArray里还不完善:

static <T> List<T> parseArray(JSONArray arrary,Class<?> cls) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException, ClassNotFoundException{
List<T> result = new ArrayList<T>();
String className = cls.getName();
for(int i=0;i<arrary.length();i++){
if(className.contains("java.lang")){
if(className.equals("java.lang.CharSequence") ||
className.equals("java.lang.String")) {
result.add((T) arrary.getString(i));
}else  if(className.equals("java.lang.Double")) {
result.add((T) ((Double)arrary.getDouble(i)));
}  else  if(className.equals("java.lang.Integer")) {
result.add((T) ((Integer)arrary.getInt(i)));
}  else  if(className.equals("java.lang.Boolean")) {
result.add((T) ((Boolean)arrary.getBoolean(i)));
}
}else{
// 解析对象
result.add((T)json2Bean(arrary.getJSONObject(i),cls));
}
}
return result;
}

public static <T> T json2Bean(JSONObject jsonObject, Class<?> cls) throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException, InstantiationException, ClassNotFoundException {
//        if (item == null) {
//          return null;
//        }
T item = (T) cls.newInstance();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
String varName = field.getName();
if (jsonObject.has(varName)) {
Object value = jsonObject.get(varName);

Class<?> currentClass = field.getType();
if(currentClass.equals(List.class)){
JSONArray array = (JSONArray)value;
String subClassName = field.getGenericType().toString().replace("java.util.List<", "");
subClassName = subClassName.substring(0,subClassName.length()-1);
//                System.out.println(subClassName);
Class<?> clasz =    Class.forName(subClassName);
//                System.out.println(z.getClass());
BeanUtils.setProperty(item, varName, parseArray(array ,clasz));

}else{
if(value instanceof JSONObject){
BeanUtils.setProperty(item, varName, json2Bean((JSONObject)value,currentClass));
}else{
if(value instanceof JSONNull){
value = null;
}
BeanUtils.setProperty(item, varName, value);
}
}
}else{
// 设置默认值
//BeanUtils.setProperty(item, varName, null);
}
}
return item;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: