json格式转换成javaBean对象的方法


这个贴可以参考。
http://bbs.csdn.net/topics/390337723
 

写道
package cn.qtone.mobile.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
* 将JSON数据转换为具体的对象
* @author jqp
*
*/
public class JsonUtil {

public static <T> T convertToObj(JSONObject jsonObject,Class<T> cla){
if(jsonObject==null) return null;
Field[] fb =cla.getDeclaredFields();
T t;
try {
t = cla.newInstance();
for(int j=0;j<fb.length;j++){
String fieldName = fb[j].getName();
String fieldNameU=fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
Method method=cla.getMethod("set"+fieldNameU, fb[j].getType());
method.invoke(t, jsonObject.get(fieldName));
}
return t;

} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

public static <T> List<T> convertToList(JSONArray jsonArray,Class<T> cla){
List<T> list=new ArrayList<T>();
if(jsonArray==null) return list;
try {
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
T t=JsonUtil.convertToObj(jsonObject, cla);
list.add(t);
}

} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

}

 



googele 提供

package com.lecast.json.until;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
 * json 简单操作的工具类
 * @author lee.li
 *
 */
public class JsonUtil{

	private static Gson gson=null;
	static{
		if(gson==null){
			gson=new Gson();
		}
	}
	private JsonUtil(){}
	/**
	 * 将对象转换成json格式
	 * @param ts
	 * @return
	 */
	public static String objectToJson(Object ts){
		String jsonStr=null;
		if(gson!=null){
			jsonStr=gson.toJson(ts);
		}
		return jsonStr;
	}
	/**
	 * 将对象转换成json格式(并自定义日期格式)
	 * @param ts
	 * @return
	 */
	public static String objectToJsonDateSerializer(Object ts,final String dateformat){
		String jsonStr=null;
		gson=new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
			public JsonElement serialize(Date src, Type typeOfSrc,
					JsonSerializationContext context) {
				SimpleDateFormat format = new SimpleDateFormat(dateformat);
				return new JsonPrimitive(format.format(src));
			}
		}).setDateFormat(dateformat).create();
		if(gson!=null){
			jsonStr=gson.toJson(ts);
		}
		return jsonStr;
	}
	/**
	 * 将json格式转换成list对象
	 * @param jsonStr
	 * @return
	 */
	public static List<?> jsonToList(String jsonStr){
		List<?> objList=null;
		if(gson!=null){
			java.lang.reflect.Type type=new com.google.gson.reflect.TypeToken<List<?>>(){}.getType();
			objList=gson.fromJson(jsonStr, type);
		}
		return objList;
	}
	/**
	 * 将json格式转换成map对象
	 * @param jsonStr
	 * @return
	 */
	public static Map<?,?> jsonToMap(String jsonStr){
		Map<?,?> objMap=null;
		if(gson!=null){
			java.lang.reflect.Type type=new com.google.gson.reflect.TypeToken<Map<?,?>>(){}.getType();
			objMap=gson.fromJson(jsonStr, type);
		}
		return objMap;
	}
	/**
	 * 将json转换成bean对象
	 * @param jsonStr
	 * @return
	 */
	public static Object  jsonToBean(String jsonStr,Class<?> cl){
		Object obj=null;
		if(gson!=null){
			obj=gson.fromJson(jsonStr, cl);
		}
		return obj;
	}
	/**
	 * 将json转换成bean对象
	 * @param jsonStr
	 * @param cl
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T  jsonToBeanDateSerializer(String jsonStr,Class<T> cl,final String pattern){
		Object obj=null;
		gson=new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
			public Date deserialize(JsonElement json, Type typeOfT,
					JsonDeserializationContext context)
					throws JsonParseException {
					SimpleDateFormat format=new SimpleDateFormat(pattern);
					String dateStr=json.getAsString();
				try {
					return format.parse(dateStr);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				return null;
			}
		}).setDateFormat(pattern).create();
		if(gson!=null){
			obj=gson.fromJson(jsonStr, cl);
		}
		return (T)obj;
	}
	/**
	 * 根据
	 * @param jsonStr
	 * @param key
	 * @return
	 */
	public static Object  getJsonValue(String jsonStr,String key){
		Object rulsObj=null;
		Map<?,?> rulsMap=jsonToMap(jsonStr);
		if(rulsMap!=null&&rulsMap.size()>0){
			rulsObj=rulsMap.get(key);
		}
		return rulsObj;
	}
	
}

 

 /** *//**
     * 从一个JSON 对象字符格式中得到一个java对象

     * @param jsonString json字符串

     * @param pojoCalss  java对象的class

     * @return

     */

    public static Object getObject4JsonString(String jsonString,Class pojoCalss)...{

        Object pojo;

        JSONObject jsonObject = JSONObject.fromObject( jsonString );  

        pojo = JSONObject.toBean(jsonObject,pojoCalss);

        return pojo;

    }

 

  /** *//**

     * 将java对象转换成json字符串

     * @param javaObj

     * @return

     */

    public static String getJsonString4JavaPOJO(Object javaObj)...{

        JSONObject json;

        json = JSONObject.fromObject(javaObj);

        return json.toString();     

    }

 

 

    /** *//**

     * 从json数组中得到相应java数组

     * @param jsonString

     * @return

     */

    public static Object[] getObjectArray4Json(String jsonString)...{

        JSONArray jsonArray = JSONArray.fromObject(jsonString);

        return jsonArray.toArray();

    }

 

  /** *//**

     * 从json对象集合表达式中得到一个java对象列表

     * @param jsonString

     * @param pojoClass

     * @return

     */

    public static List getList4Json(String jsonString, Class pojoClass)...{

        JSONArray jsonArray = JSONArray.fromObject(jsonString);

        JSONObject jsonObject;

        Object pojoValue; 

        List list = new ArrayList();

        for ( int i = 0 ; i<jsonArray.size(); i++)...{ 

            jsonObject = jsonArray.getJSONObject(i);

            pojoValue = JSONObject.toBean(jsonObject,pojoClass);

            list.add(pojoValue);

        }

        return list;

    }

 

package dsh.bikegis.tool;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.List;

/**
 * json的操作类
 * @author NanGuoCan
 *
 */
public class JsonUtil {
	  
	    /**
	      * @param object
	      *             任意对象
	      * @return java.lang.String
	      */  
	    public static String objectToJson(Object object) {   
	         StringBuilder json = new StringBuilder();   
	        if (object == null) {   
	             json.append("\"\"");   
	         } else if (object instanceof String || object instanceof Integer) { 
	             json.append("\"").append(object.toString()).append("\"");  
	         } else {   
	             json.append(beanToJson(object));   
	         }   
	        return json.toString();   
	     }   
	  
	    /**
	      * 功能描述:传入任意一个 javabean 对象生成一个指定规格的字符串
	      *
	      * @param bean
	      *             bean对象
	      * @return String
	      */  
	    public static String beanToJson(Object bean) {   
	         StringBuilder json = new StringBuilder();   
	         json.append("{");   
	         PropertyDescriptor[] props = null;   
	        try {   
	             props = Introspector.getBeanInfo(bean.getClass(), Object.class)   
	                     .getPropertyDescriptors();   
	         } catch (IntrospectionException e) {   
	         }   
	        if (props != null) {   
	            for (int i = 0; i < props.length; i++) {   
	                try {  
	                     String name = objectToJson(props[i].getName());   
	                     String value = objectToJson(props[i].getReadMethod().invoke(bean));  
	                     json.append(name);   
	                     json.append(":");   
	                     json.append(value);   
	                     json.append(",");  
	                 } catch (Exception e) {   
	                 }   
	             }   
	             json.setCharAt(json.length() - 1, '}');   
	         } else {   
	             json.append("}");   
	         }   
	        return json.toString();   
	     }   
	  
	    /**
	      * 功能描述:通过传入一个列表对象,调用指定方法将列表中的数据生成一个JSON规格指定字符串
	      *
	      * @param list
	      *             列表对象
	      * @return java.lang.String
	      */  
	    public static String listToJson(List<?> list) {   
	         StringBuilder json = new StringBuilder();   
	         json.append("[");   
	        if (list != null && list.size() > 0) {   
	            for (Object obj : list) {   
	                 json.append(objectToJson(obj));   
	                 json.append(",");   
	             }   
	             json.setCharAt(json.length() - 1, ']');   
	         } else {   
	             json.append("]");   
	         }   
	        return json.toString();   
	     }
}

 

 

package com.jetsum.util;

import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import antlr.RecognitionException;
import antlr.TokenStreamException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;

public class JsonUtil {

 /**
  * JAVA对象转换成JSON字符串
  * @param obj
  * @return
  * @throws MapperException
  */ 
 public static String objectToJsonStr(Object obj) throws MapperException{
        JSONValue jsonValue = JSONMapper.toJSON(obj);  
        String jsonStr = jsonValue.render(false);
        return jsonStr;
 }
 
 /**
  * 重载objectToJsonStr方法
  * @param obj 需要转换的JAVA对象
  * @param format 是否格式化
  * @return
  * @throws MapperException
  */
 public static String objectToJsonStr(Object obj,boolean format) throws MapperException{
        JSONValue jsonValue = JSONMapper.toJSON(obj);  
        String jsonStr = jsonValue.render(format);
        return jsonStr;
 } 
 
 /**
  * JSON字符串转换成JAVA对象
  * @param jsonStr
  * @param cla
  * @return
  * @throws MapperException
  * @throws TokenStreamException
  * @throws RecognitionException
  */
 @SuppressWarnings({ "rawtypes", "unchecked" })
 public static Object jsonStrToObject(String jsonStr,Class<?> cla) throws MapperException, TokenStreamException, RecognitionException{
  Object obj = null;
  try{
         JSONParser parser = new JSONParser(new StringReader(jsonStr));    
         JSONValue jsonValue = parser.nextValue();           
         if(jsonValue instanceof com.sdicons.json.model.JSONArray){
          List list = new ArrayList();
          JSONArray jsonArray = (JSONArray) jsonValue;
          for(int i=0;i<jsonArray.size();i++){
           JSONValue jsonObj = jsonArray.get(i);
           Object javaObj = JSONMapper.toJava(jsonObj,cla); 
           list.add(javaObj);
          }
          obj = list;
         }else if(jsonValue instanceof com.sdicons.json.model.JSONObject){
          obj = JSONMapper.toJava(jsonValue,cla); 
         }else{
          obj = jsonValue;
         }
        }catch(Exception e){
         e.printStackTrace();
        }
        return obj; 
 }
 
 /**
  * 将JAVA对象转换成JSON字符串
  * @param obj
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 @SuppressWarnings("rawtypes")
 public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
  if(obj==null){
   return "null";
  }
  String jsonStr = "{";
  Class<?> cla = obj.getClass();
  Field fields[] = cla.getDeclaredFields();
  for (Field field : fields) {
   field.setAccessible(true);
   if(field.getType() == long.class){
    jsonStr += """+field.getName()+"":"+field.getLong(obj)+",";
   }else if(field.getType() == double.class){
    jsonStr += """+field.getName()+"":"+field.getDouble(obj)+",";
   }else if(field.getType() == float.class){
    jsonStr += """+field.getName()+"":"+field.getFloat(obj)+",";
   }else if(field.getType() == int.class){
    jsonStr += """+field.getName()+"":"+field.getInt(obj)+",";
   }else if(field.getType() == boolean.class){
    jsonStr += """+field.getName()+"":"+field.getBoolean(obj)+",";
   }else if(field.getType() == Integer.class||field.getType() == Boolean.class
     ||field.getType() == Double.class||field.getType() == Float.class     
     ||field.getType() == Long.class){    
    jsonStr += """+field.getName()+"":"+field.get(obj)+",";
   }else if(field.getType() == String.class){
    jsonStr += """+field.getName()+"":""+field.get(obj)+"",";
   }else if(field.getType() == List.class){
    String value = simpleListToJsonStr((List<?>)field.get(obj),claList);
    jsonStr += """+field.getName()+"":"+value+",";    
   }else{  
    if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){
     String value = simpleObjectToJsonStr(field.get(obj),claList);
     jsonStr += """+field.getName()+"":"+value+",";     
    }else{
     jsonStr += """+field.getName()+"":null,";
    }
   }
  }
  jsonStr = jsonStr.substring(0,jsonStr.length()-1);
  jsonStr += "}";
   return jsonStr;  
 }
 
 /**
  * 将JAVA的LIST转换成JSON字符串
  * @param list
  * @return
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 @SuppressWarnings("rawtypes")
 public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
  if(list==null||list.size()==0){
   return "[]";
  }
  String jsonStr = "[";
  for (Object object : list) {
   jsonStr += simpleObjectToJsonStr(object,claList)+",";
  }
  jsonStr = jsonStr.substring(0,jsonStr.length()-1);
  jsonStr += "]";  
  return jsonStr;
 } 
 
 /**
  * 将JAVA的MAP转换成JSON字符串,
  * 只转换第一层数据
  * @param map
  * @return
  */
 public static String simpleMapToJsonStr(Map<?,?> map){
  if(map==null||map.isEmpty()){
   return "null";
  }
  String jsonStr = "{";
  Set<?> keySet = map.keySet();
  for (Object key : keySet) {
   jsonStr += """+key+"":""+map.get(key)+"",";  
  }
  jsonStr = jsonStr.substring(0,jsonStr.length()-1);
  jsonStr += "}";
  return jsonStr;
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值