1. 程式人生 > >Ext Grid 實現批量新增或者修改

Ext Grid 實現批量新增或者修改

將ExtJS Grid 中的record逐一轉化為Bean,實現批量的新增或者修改

package com.hwasun.utils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.junit.Test;

/**
 * 將Ext中Store的data資料轉化為Java中的List
 * @author JLee v .10
 * @since 2011-2-25
 * @function 主要是為了ext中可編輯的grid實現批量新增與修改
 * 將註解的地方放開可以測試一下
 */
public class Json2List {

	@Test
	//將Store中的data(即:多個record)轉化為多個bean
	public Object JSON4Hibernate(Class clazz ,String json)throws Exception{
		System.out.println("將要解析的JSON串"+json);
		List list = new ArrayList();
		
		JSONObject jsonObjSplit = JSONObject.fromObject(json);
		JSONArray ja = jsonObjSplit.getJSONArray("data");
		for (int i = 0; i < ja.size(); i++) {
			
			Object bean = clazz.newInstance() ;
			Class c = bean.getClass() ;
			Field[] fs = c.getDeclaredFields();
			
			JSONObject jsonObject = (JSONObject) ja.get(i);
			for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
				String key = (String) iter.next();
				String value = jsonObject.getString(key);
				//為了父類賦值 適應繼承 過來的ID
				if("id".equals(key)){
					modifyId(bean,"id",value) ;
				}
				//為自己的實體每個屬性賦值
				for (Field f : fs) {
					if(f.getName().equals(key)){
						Object vType = convertValueType(bean,f ,value);
						mf1(bean,f.getName(),vType);
					}
				}
			}
			list.add(bean) ;
		}
		return list ;
	}
	
	//對bean的屬性進行判斷,然後將JSON中的值轉化為對應的型別
	public Object convertValueType(Object o,Field f, String value) throws Exception {
		Object ov = null ;
		String fieldTypeName = f.getType().getName();
		if (fieldTypeName.equals("int")||fieldTypeName.equals("java.lang.Integer")) {
			ov = value!=null&&value!="null"&&!"".equals(value)?Integer.parseInt(value):null ;
		} else if (fieldTypeName.equals("long")||fieldTypeName.equals("java.lang.Long")) {
			ov = value!=null&&value!="null"&&!"".equals(value)?Long.parseLong(value):null ;
		} else if (fieldTypeName.equals("float")||fieldTypeName.equals("java.lang.Float")) {
			ov = value!=null&&value!="null"&&!"".equals(value)?Float.parseFloat(value):null ;
		} else if (fieldTypeName.equals("double")||fieldTypeName.equals("java.lang.Double")) {
			ov = value!=null&&value!="null"&&!"".equals(value)?Double.parseDouble(value):null ;
		} else if (fieldTypeName.equals("boolean")||fieldTypeName.equals("java.lang.Boolean")) {
			ov = value!=null&&value!="null"&&!"".equals(value)?Boolean.parseBoolean(value):null ;
		} else if (fieldTypeName.equals("java.util.Date")) {
			if(value.length()>11){
                                                    ov = value!=null&&value!="null"&&!"".equals(value)?new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value):null ;
                                                }else{
                                                    ov = value!=null&&value!="null"&&!"".equals(value)?new SimpleDateFormat("yyyy-MM-dd").parse(value):null ;
                                                }		
                                } else if (fieldTypeName.equals("java.lang.String")) {
			ov = (String)value ;
		} else if (fieldTypeName.equals("java.lang.Object")) {
			ov = (Object)value ;
		} else {
			 Field oField = o.getClass().getDeclaredField(f.getName());
			 if (oField != null) {   
                oField.setAccessible(true);   
                Object entity = oField.get(o);   
                if (entity == null) {
                    entity = oField.getType().newInstance();   
                }
                ov = json2Object(value ,entity);
            }   
		}
		return ov ;
	}

	//將{name:"jlee",sex:"male",age:18,job:"student"}json格式付給bean中對應的Object屬性
	public Object json2Object(String json ,Object entity)throws Exception{
		Class c = entity.getClass();
		Field[] fs = c.getDeclaredFields();
		if("[".equals(json.substring(0, 1))){
			json = json.substring(1) ;
		}
		if("]".equals(json.substring(json.length()-1))){
			json = json.substring(0,json.length()-1) ;
		}
	    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(json);
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String)iter.next();
			String value = jsonObject .getString(key) ;
                        //為了父類賦值 適應繼承 過來的ID
			if("id".equals(key)){
				modifyId(entity,"id",value) ;
			}
			for (Field f : fs) {
				if(f.getName().equals(key)){
					Object vType = convertValueType(entity,f ,value);
					mf1(entity,f.getName(),vType);
				}
			}
		}
		return entity ;
	}
	
	//修改bean的屬性值
	public void mf1(Object o , String fieldName ,Object newValue)throws Exception {
		Class c = o.getClass() ;
		Field f = c.getDeclaredField(fieldName);
		f.setAccessible(true);
		f.set(o, newValue);
	}

	//修改父類的 ID 值
	public void modifyId(Object bean ,String fieldName ,String value) throws Exception{
		Class c = bean.getClass().getSuperclass() ;
		Field[] array = c.getDeclaredFields() ;
		for(Field _f : array){
			if(_f.getName().equals(fieldName)){
				Field f = c.getDeclaredField(fieldName);
				Object vType = convertValueType(bean,f ,value);
				f.setAccessible(true);
				f.set(bean, vType);
			}
		}
	}
	
	public static void main(String[] args)throws Exception {
		String json = "{data:[" +
						"{id:'',name:'Lily',amount:'100',num:'12.3',isRight:'true',myTest:{id:'1',name:'test1',myTest:{id:'32'}}}," +
						"{id:'4',name:'Jim',amount:'200',num:'12.4',isRight:'false',myTest:{id:'2',name:'test2',myTest:{id:'3'}}}" +
					  "]}";
		Json2List mj = new Json2List();
		Object list = mj.JSON4Hibernate(MyBean.class,json);
		for(MyBean mb : (List<MyBean>)list){
			System.out.println("解析之後的Bean:"+mb.toString());
		}
	}
	
}



 class MyBean {

	private Integer id ;
	private String name ;
	private Long amount ;
	private boolean isRight ;
	private double num ;
	
	private MyTest myTest ;
	
	public MyTest getMyTest() {
		return myTest;
	}
	public void setMyTest(MyTest myTest) {
		this.myTest = myTest;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Long getAmount() {
		return amount;
	}
	public void setAmount(Long amount) {
		this.amount = amount;
	}
	public boolean getIsRight() {
		return isRight;
	}
	public void setIsRight(boolean isRight) {
		this.isRight = isRight;
	}
	public double getNum() {
		return num;
	}
	public void setNum(double num) {
		this.num = num;
	}
	
	@Override
	public String toString() {
		return "bean的值   { id:"+this.getId()+"   name:"+this.getName()
				+"   num:"+this.getNum()+"  amount:"+this.getAmount() 
				+ "  isRight:" + this.getIsRight()+ "   myTest:"+this.getMyTest().toString()+" }";
	}
	
}

 

  class MyTest {

 	private int id ;
 	
 	private String name ;
 	
 	private MyTest myTest ;
 	

 	public MyTest getMyTest() {
		return myTest;
	}

	public void setMyTest(MyTest myTest) {
		this.myTest = myTest;
	}

	public int getId() {
 		return id;
 	}

 	public void setId(int id) {
 		this.id = id;
 	}

 	public String getName() {
 		return name;
 	}

 	public void setName(String name) {
 		this.name = name;
 	}
 	
 	@Override
 	public String toString() {
 		return "{id:"+this.getId()+","+"name:"+this.getName()+"  myTest:{  id:"+this.getMyTest().getId()+"}"+"  }";
 	}
 }

執行結果:

將要解析的JSON串{data:[{id:'',name:'Lily',amount:'100',num:'12.3',isRight:'true',myTest:{id:'1',name:'test1',myTest:{id:'32'}}},{id:'4',name:'Jim',amount:'200',num:'12.4',isRight:'false',myTest:{id:'2',name:'test2',myTest:{id:'3'}}}]}
解析之後的Bean:bean的值   { id:null   name:Lily   num:12.3  amount:100  isRight:true   myTest:{id:1,name:test1  myTest:{  id:32}  } }
解析之後的Bean:bean的值   { id:4   name:Jim   num:12.4  amount:200  isRight:false   myTest:{id:2,name:test2  myTest:{  id:3}  } }