通过java内省,把json对象转为Object
2012-09-10 22:57
369 查看
package reflect; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; /** * 自省方式 * @author Jeremy * */ public class JsonUtils { /** * JSONObject 转自定义对象 * @param json * @param beanClass * @return */ public static <T> T jsonToBean(JSONObject json, Class<T> beanClass) { T retObj = null; JSONArray jsonPropertyNames = json.names(); List<String> propertyNames = getPropertyNames(beanClass); try { // 实例化 retObj = beanClass.newInstance(); for (int i = 0; i < jsonPropertyNames.length(); i++) { String propName = jsonPropertyNames.getString(i); Object value = json.get(propName); // 如果类中有该json对象的属性,才获取 if (propertyNames.contains(propName)) { PropertyDescriptor pd = new PropertyDescriptor(propName, beanClass); Method m = pd.getWriteMethod(); if (m != null) { m.invoke(retObj, value); } } } } catch (Exception e) { e.printStackTrace(); } return retObj; } public static List<String> getPropertyNames(Class<?> clazz) { List<String> propNames = new ArrayList<String>(); try { BeanInfo bi = Introspector.getBeanInfo(clazz); PropertyDescriptor[] pd = bi.getPropertyDescriptors(); for ( int i=0;i<pd.length;i++){ PropertyDescriptor p = pd[i]; String propName = p.getName(); propNames.add(propName); } } catch (Exception e) { e.printStackTrace(); } return propNames; } }
相关文章推荐
- 如何通过Java代码将JSONObject转换为对象
- Atiitt 对象转换json 序列化规范 Java 循环引用的解决 设置序列化层次深度 去除不必的属性 太长不方便月度 jsonObject.remove("num1"); Prety fo
- 对象中含有java.util.Date时使用JSONArray.fromObject时时间显示问题
- java方式的将java对象以及list或者map转化为json数据,json转换为object或者map
- 利用Java反射实现普通对象到JSONObject的转换
- JSONObject转换为java对象
- 百度天气api开发 全解析xml和json格式 使用json-lib jsonObject、 Gson 方式把json 转换成 java对象
- web服务端使用JSONArrayy或JSONObject转json字符串为Java对象或数组
- Flex通过RemoteObject访问远程Java对象
- 使用 jackson ObjectMapper将java对象转换为json对象
- Java gson使用 将Java对象转为Json 并 Json转回Java对象
- 【Java】通过JSONObject获取数据库查询结果
- JSON转为Java对象时报的错
- Java gson使用 将Java对象转为Json 并 Json转回Java对象
- Java对象转为json
- JSON,XML,JavaObject对象互相转换…
- java服务器用struts2通过JSONObject返回json数据库
- 通过jsonObject toBean方法,实现对象的实例化
- java中map转为object对象
- C#(服务器)与Java(客户端)通过Socket传递对象(序列化 json)