java更新json数据类型_根据jsonobject中的部分数据更新javabean中对应的属性[PATCH]

springmvc restful api中的patch方法中使用到的一个类分享给筒子们:

欢迎批评指正

import java.lang.reflect.Field;

import java.util.Iterator;

import net.sf.json.JSONObject;

public class JavaBeanUtils {

/**

* 根据json中的部分数据更新bean中对应的属性

* @param bean

* @param json

* @return

* @throws Exception

*/

public static void patch(T bean,JSONObject json) throws Exception{

Field[] fields=bean.getClass().getDeclaredFields();

for(Field field:fields){

//System.out.println(field.getName());

Iterator iterator = json.keys();

while(iterator.hasNext()){

String key = (String) iterator.next();

if(field.getName().equals(key)){

String value = json.getString(key);

String type = field.getType().toString();//得到此属性的类型

field.setAccessible(true);//设置些属性是可以访问的

// 赋值(目前只判断了以下几种,如有其他的请自行扩展)

if (type.endsWith("String")) {

field.set(bean,value);

}else if(type.endsWith("float")){

field.set(bean,Float.valueOf(value));

}else if(type.endsWith("int")){

field.set(bean,Integer.parseInt(value));

}

}

}

}

}

}

获取属性的相关说明:

http://www.jb51.cc/article/p-wfxuojyr-es.html

getFields()获得某个类的所有的公共(public)的字段,包括父类。

getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。

同样类似的还有getConstructors()和getDeclaredConstructors(),getMethods()和getDeclaredMethods()。

其他实现:

xxxx source = new xxxx();

Method[] sourceMethods = source.getClass().getMethods();

for(int i=0;i

if(sourceMethods[i].getName().startsWith("get")){

lsName = sourceMethods[i].getName().substring(3); // 属性

Object loValue = sourceMethods[i].invoke(source,null); // 值

String lsSourceType = sourceMethods[i].getReturnType().getName(); //类型

}

}

相关文章

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值