这个贴可以参考。
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;
}
}
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; } }
相关推荐
一个自制的json转换jar 直接调用JsonFactory.toJson()方法可将javaBean转换成json
忽略字段的首字母大小写,将json字符串转成javabean对象,解决Java对象中属性中首字母大写而取不到值(取到的值为空)的问题 忽略字段的首字母大小写,将json字符串转成List,解决Java对象中属性中首字母大写而取不...
将JavaBean对象与Json字符串相互转换,将Java集合与Json字符串集合相互转换。
最近在研究Webservice的时候遇到一个问题,把java对象转化问json后传过去,接受的是String类型,怎么恢复到原来的java对象呢,后来再一个项目中看到了转换方法,转换顺序为javaBean--jsonObject--jsonString,还原...
json对象与javabean相互转化 JSONObject jsonObj=JSONObject.fromObject(s);//将字符串转化为json对象 //写数据库处理 ObjBean bean=(ObjBean)JSONObject.toBean(jsonObj,ObjBean.class); ObjBean bean=new ...
通过该工具可以将javascript提交的json字符串,转换成JSON对象,再进一步转换成Javabean对象或集合,反之亦然,大大简化了编码的难度
主要介绍了FastJson对于JSON格式字符串、JSON对象及JavaBean之间的相互转换,非常不错,具有参考借鉴价值,需要的朋友可以参考下
1.JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换 2.JSONObject:fastJson提供的json对象 3.JSONArray:fastJson提供json数组对象 --------------------- 作者:superlovelei 来源:...
ajax 与 java 之间使用 json 交换数据,JSON到Java 对象的转换,Java对象到JSON的转换。 JSONObject object=new JSONObject(javaBean); String jsonStr=object.toString();
1.FastJson的介绍: JSON协议使用方便,越来越流行,...1.JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换 2.JSONObject:fastJson提供的json对象 3.JSONArray:fastJson提供json数组对象
主要介绍了javabean转成json字符并首字母大写代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
里面有详细的json字符串和java对象(JavaBean,HashMap,ArrayList,Array...)的互相转化
此文档包含了对JSON的由来,组成以及fastJSON与javaBean对象的相互转换的详细描述,还具有在日常工作中经过总结而写的工具类,在工作中非常实用
在SpringMVC中使用JSON需要引入...转化json格式数据成为javabean对象 2.commons-beanutils-1.7.0.jar 3.commons-collections-3.2.jar 4.commons-lang-2.3.jar 5.commons-logging-1.0.4.jar 6.ezmorph-1.0.4.jar
Tomjson,一个"短小精悍"的 json 解析库,tomjson使用Java语言编写,主要作用是把Java对象(JavaBean)序列化为json格式字符串,将json格式字符串序列化为相对应的Java对象(JavaBean)。项目地址:...
解决javascript向服务端提交json数据格式时的拼装问题。 内部使用javabean模式包装javascript对象,使用继承获取 转换json的方法。
FastJson对于json格式字符串的解析主要用到了下面三个类: 1.JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换 2.JSONObject:fastJson提供的json对象 3.JSONArray:fastJson提供json数组...
长得有点丑,朋友圈子内很多人在使用了,主要功能在很简单的界面能够支持post和get方法传值获取返回值,并格式化显示JSON数据,本来还有一个版本是花了大力气写的JSON转换JavaBean对象的功能,但是后来基本上都没有...
Alibaba Fastjson包。 对JSON格式字符串与JSON对象及javaBean之间做转换。
fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。