对JSON数据进行解析,很实用的工具类

package com.utils;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.processors.JsonBeanProcessor;
import net.sf.json.util.CycleDetectionStrategy;
/**
 * 对json数据进行解析,将对象转化为json数据操作 工具类
 * 
 */
public class JsonUtils {
private static String[]dirName;

public static void setDirName(String[] dirName) {
JsonUtils.dirName = dirName;
}
public static List<Class> list=new ArrayList<Class>();
static{
list.add(OneToOne.class);
list.add(OneToMany.class);
list.add(ManyToOne.class);
list.add(ManyToMany.class);
}
public static  List<Class> userlist=new ArrayList<Class>();
private static JsonConfig jsonConfig = new JsonConfig();
/**
* 初始化json变量的初始值
*/
static {
jsonConfig.setExcludes(new String[] { "handler",
"hibernateLazyInitializer" });
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
jsonConfig.registerJsonBeanProcessor(java.sql.Date.class, new DateJsonValueProcessor());
jsonConfig.setIgnoreDefaultExcludes(true);
jsonConfig.setAllowNonStringKeys(true);
jsonConfig.registerDefaultValueProcessor(Boolean.class,
new DefaultValueProcessor() {
public Object getDefaultValue(Class type) {
return JSONNull.getInstance();
}
});
}
/**
* 将对象转换为json字符串,并将数据响应到界面

* @param response
*            HttpServletResponse对象
* @param obj
*            对象实例(该对象是一级结构的数据库实体类或者自己封装的不包含实体类的一级或多级新对象)
*/
public static void printJsonStringFromObject(HttpServletResponse response,
Object obj) {
PrintWriter writer = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
writer = response.getWriter();
} catch (IOException e) {
System.out.print(e.getMessage());
}
String objString = obj.getClass().toString().substring(6);
jsonConfig.setExcludes(getExcludeFields(objString));
writer.print(JSONObject.fromObject(obj, jsonConfig).toString());
userlist.clear();
if (writer != null)
writer.close();
}
/**
* 将对象转换为json字符串,并将数据响应到界面

* @param response
*            HttpServletResponse对象
* @param obj
*            对象实例(该对象是自己封装的包含任何实体类对象的多层级的新对象)
* @param exclude
*            该对象的某一层所包含得一对多,多对一,一对一,多对多关系的数据库实体类名称的字符串数组(不包含包名)
*/
public static void printJsonStringFromObjectWithExclude(
HttpServletResponse response, Object obj, String[] exclude) {
PrintWriter writer = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
writer = response.getWriter();
} catch (IOException e) {
System.out.print(e.getMessage());
}
String[] arrayDate = new String[exclude.length + 1];
String objString = obj.getClass().toString().substring(6);
for (int i = 0; i < exclude.length; i++){
if(exclude[i].indexOf(".")==-1){
for(int k=0;k<dirName.length;k++)
try {
Class.forName(dirName[k] + exclude[i]);
arrayDate[i] = (dirName[k]+ exclude[i]);
break;
} catch (ClassNotFoundException e1) {
}
}
else arrayDate[i] = (exclude[i]);
}
arrayDate[exclude.length] = objString;
jsonConfig.setExcludes(getExcludeFieldsList(arrayDate));
writer.print(JSONObject.fromObject(obj, jsonConfig).toString());
userlist.clear();
if (writer != null)
writer.close();
}
/**
* 获取对象的json字符串

* @param obj
*            对象实例(该对象是一级结构的数据库实体类或者自己封装的不包含实体类的一级或多级新对象)
* @return json字符串
*/
public static String toJsonStringFromObject(Object obj) {
String objString = obj.getClass().toString().substring(6);
jsonConfig.setExcludes(getExcludeFields(objString));
String result = JSONObject.fromObject(obj, jsonConfig).toString();
userlist.clear();
return result;
}
/**
* 获取对象的json字符串

* @param obj对象实例
*            (该对象是自己封装的包含任何实体类对象的多层级的新对象)
* @param exclude该对象的某一层所包含得一对多
*            ,多对一,一对一,多对多关系的数据库实体类名称的字符串数组(不包含包名)
* @return json字符串
*/
public static String toJsonStringFromObjectWithExclude(Object obj,
String[] exclude) {
String[] arrayDate = new String[exclude.length + 1];
String objString = obj.getClass().toString().substring(6);
for (int i = 0; i < exclude.length; i++)
{
if(exclude[i].indexOf(".")==-1){
for(int k=0;k<dirName.length;k++)
try {
Class.forName(dirName[k] + exclude[i]);
arrayDate[i] = (dirName[k]+ exclude[i]);
break;
} catch (ClassNotFoundException e1) {
}
}else arrayDate[i] = (exclude[i]);
}
arrayDate[exclude.length] = objString;
jsonConfig.setExcludes(getExcludeFieldsList(arrayDate));
String result = JSONObject.fromObject(obj, jsonConfig).toString();
userlist.clear();
return result;
}
/**
* 将列表类型的对象转换成json

* @param obj
*            对象列表(该对象是一级结构的数据库实体类或者自己封装的不包含实体类的一级或多级新对象)
* @return json字符串
*/
public static String toJsonStringFromArrayObject(Object obj) {
String objString = obj.getClass().toString().substring(6);
jsonConfig.setExcludes(getExcludeFields(objString));
String result = JSONArray.fromObject(obj, jsonConfig).toString();
userlist.clear();
return result;
}
/**
 * 将列表类型的对象转换成json
 * @param obj对象列表(该对象是自己封装的包含任何实体类对象的多层级的新对象)
 * @param exclude该对象的某一层所包含得一对多,多对一,一对一,多对多关系的数据库实体类名称的字符串数组(不包含包名)
 * @return json字符串
 */
public static String toJsonStringFromArrayObjectWithExclude(Object obj,
String[] exclude) {
String[] arrayDate = new String[exclude.length + 1];
String objString = obj.getClass().toString().substring(6);
for (int i = 0; i < exclude.length; i++)
{  if(exclude[i].indexOf(".")==-1){
for(int k=0;k<dirName.length;k++)
try {
Class.forName(dirName[k] + exclude[i]);
arrayDate[i] = (dirName[k]+ exclude[i]);
break;
} catch (ClassNotFoundException e1) {
}
}else arrayDate[i] = (exclude[i]);
}
arrayDate[exclude.length] = objString;
jsonConfig.setExcludes(getExcludeFieldsList(arrayDate));
String result = JSONArray.fromObject(obj, jsonConfig).toString();
userlist.clear();
return result;
}
/**
* 将列表类型的对象转换成数组,并响应到界面

* @param response
*            HttpServletResponse对象
* @param obj
*            对象实例(该对象只可以是数据库实体类集合或者自己封装的不包含实体类对象的新对象集合)
*/
public static void printJsonStringFromArrayObject(
HttpServletResponse response, Object obj) {
PrintWriter writer = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
writer = response.getWriter();
} catch (IOException e) {
System.out.print(e.getMessage());
}
String objString = obj.getClass().toString().substring(6);
jsonConfig.setExcludes(getExcludeFields(objString));
writer.print(JSONArray.fromObject(obj, jsonConfig).toString());
userlist.clear();
if (writer != null)
writer.close();
}
/**
* 将列表类型的对象转换成数组,并响应到界面

* @param response
*            HttpServletResponse对象
* @param obj
*            对象实例(该对象可以是数据库实体类或者自己封装的包含任何实体类对象的新对象)
* @param exclude
*            该对象中包含一对多,多对一,一对一,多对多关系的数据库实体类名称的字符串数组
*/
public static void printJsonStringFromArrayObjectWithExclude(
HttpServletResponse response, Object obj, String[] exclude) {
PrintWriter writer = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
writer = response.getWriter();
} catch (IOException e) {
System.out.print(e.getMessage());
}
String[] arrayDate = new String[exclude.length + 1];
String objString = obj.getClass().toString().substring(6);
for (int i = 0; i < exclude.length; i++)
{   if(exclude[i].indexOf(".")==-1){
for(int k=0;k<dirName.length;k++)
try {
Class.forName(dirName[k] + exclude[i]);
arrayDate[i] = (dirName[k]+ exclude[i]);
break;
} catch (ClassNotFoundException e1) {
}
}else arrayDate[i] = (exclude[i]);
}
arrayDate[exclude.length] = objString;
String[]exc=getExcludeFieldsList(arrayDate);
jsonConfig.setExcludes(exc);
writer.print(JSONArray.fromObject(obj, jsonConfig).toString());
userlist.clear();
if (writer != null)
writer.close();
}
/**
* 将数据直接响应到前台界面

* @param response
*            HttpServletResponse对象
* @param obj
*            要传递的数据,多是一些状态值
*/
public static void printCommonObject(HttpServletResponse response,
String obj) {
PrintWriter writer = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
writer = response.getWriter();
} catch (IOException e) {
System.out.print(e.getMessage());
}
writer.print(obj);
try{
if (writer != null)
writer.close();
}catch(Exception e){
System.out.print(e.getMessage());
}
}
/**
* 将xml数据直接响应到前台界面

* @param response
*            HttpServletResponse对象
* @param obj
*            要传递的xml数据
*/
public static void printCommonXmlObject(HttpServletResponse response,
String obj) {
PrintWriter writer = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("content-type", "text/xml;charset=UTF-8");
writer = response.getWriter();
} catch (IOException e) {
System.out.print(e.getMessage());
}
writer.print(obj);
if (writer != null)
writer.close();
}
/**
* 将json字符串指定内容转换为Object对象实例

* @param jsonString
*            json字符串
* @param objectName
*            字段名称
* @return 字段的值
*/
public static Object getObjectFromJsonString(String jsonString,
String objectName) {
JSONObject objs = JSONObject.fromObject(jsonString);
JSONObject obj = objs.getJSONObject(objectName);
return obj;
}
/**
* 将json字符串转换为Object对象实例

* @param jsonString
*            json字符串
* @return 字段的值
*/
public static Object getObjectFromJsonString(String jsonString) {
JSONObject objs = JSONObject.fromObject(jsonString);
return objs;
}
/**
* 将json字符串指定内容转换为boolean类型的

* @param jsonString
*            json字符串
* @param objectName
*            字段名称
* @return 字段的值
*/
public static Boolean getBooleanFromJsonString(String jsonString,
String objectName) {
JSONObject objs = JSONObject.fromObject(jsonString);
Boolean obj = objs.getBoolean(objectName);
return obj;
}
/**
* 将json字符串转指定内容转换为字符串

* @param jsonString
*            json字符串
* @param objectName
*            字段名称
* @return 字段的值
*/
public static String getStringFromJsonString(String jsonString,
String objectName) {
JSONObject objs = JSONObject.fromObject(jsonString);
String obj = objs.getString(objectName);
return obj;
}
/**
* 将json字符串指定字段转换为数字

* @param jsonString
*            json字符串
* @param objectName
*            字段名称
* @return 字段的值
*/
public static Integer getIntegerFromJsonString(String jsonString,
String objectName) {
JSONObject objs = JSONObject.fromObject(jsonString);
Integer obj = objs.getInt(objectName);
return obj;
}
/**
* 将json字符串的指定的值转换为单精度浮点数

* @param jsonString
*            json字符串
* @param objectName
*            字段名称
* @return 字段的值
*/
public static Float getFloatFromJsonString(String jsonString,
String objectName) {
JSONObject objs = JSONObject.fromObject(jsonString);
Float obj = Float.parseFloat(objs.getString(objectName));
return obj;
}
/**
* 将json字符串的指定的值转换为双精度浮点数

* @param jsonString
*            json字符串
* @param objectName
*            字段名称
* @return 字段的值
*/
public static Double getDoubleFromJsonString(String jsonString,
String objectName) {
JSONObject objs = JSONObject.fromObject(jsonString);
Double obj = objs.getDouble(objectName);
return obj;
}
/**
* 将json字符串转换为指定的java对象

* @param jsonString
*            json字符串
* @param clas
*            对象类型
* @return 对象实例
*/
public static <T> T fromJsonStringToJavaObject(String jsonString,
Class<T> clas) {
JSONObject objs = JSONObject.fromObject(jsonString);
T t = null;
try {
t = clas.newInstance();
} catch (InstantiationException e2) {
e2.printStackTrace();
} catch (IllegalAccessException e2) {
e2.printStackTrace();
}
// // 通过默认构造方法创建一个新的对象
// Object objectCopy = clas.getConstructor(new
// Class[]{}).newInstance(new Object[]{});
Field fields[] = clas.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];


String fieldName = field.getName();
Class type = field.getType();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
// 获得和属性对应的getXXX()方法的名字
// String getMethodName = "get" + firstLetter +
// fieldName.substring(1);
// 获得和属性对应的setXXX()方法的名字
String setMethodName = "set" + firstLetter + fieldName.substring(1);
// 获得和属性对应的getXXX()方法
// Method getMethod = classType.getMethod(getMethodName, new
// Class[]{});
// 获得和属性对应的setXXX()方法
Method setMethod = null;
try {
setMethod = clas.getMethod(setMethodName, new Class[] { type });
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
}
// 调用拷贝对象的setXXX()方法
JSONObject objfiled = objs.getJSONObject(fieldName);
// Object fileValue=null;
// if(type==String.class){
// }
try {
setMethod.invoke(t, new Object[] { objfiled });
} catch (IllegalAccessException e) {
System.out.print(e.getMessage());
} catch (IllegalArgumentException e) {
System.out.print(e.getMessage());
} catch (InvocationTargetException e) {
System.out.print(e.getMessage());
}
}
return t;
}
/**
* 格式化json字符串,去掉无用的属性,并转换为json字符串

* @param jsonString
*            json字符串
* @param excludes
*            不包含在json字符串中的字段列表
* @return 格式化后的joson字符串
*/
public static String formatJsonStringWithExcludeFields(String jsonString,
String[] excludes) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(jsonString,
jsonConfig);
return jsonObject.toString();
}
/**
* 格式化List列表,去掉无用的属性,并转换为json字符串

* @param jsonList
*            列表数据
* @param excludes
*            不包含在json字符串中的字段列表
* @return 格式化后的joson字符串
*/
public static String formatListWithExcludeFields(List jsonList,
String[] excludes) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
return JSONArray.fromObject(jsonList, jsonConfig).toString();
}
/**
* 格式化List列表,去掉相关类中存在多对多关系映射的属性,并转换为json字符串
* @param jsonList 列表数据
* @param exclude该对象的某一层所包含得一对多,多对一,一对一,多对多关系的数据库实体类名称的字符串数组(不包含包名)
* @return 格式化后的joson字符串
*/
public static String formatListWithExcludeClass(List jsonList,
String[] exclude) {
for(int i=0;i<exclude.length;i++)
{     if(exclude[i].indexOf(".")==-1){
for(int k=0;k<dirName.length;k++)
try {
Class.forName(dirName[k] + exclude[i]);
exclude[i] = (dirName[k]+ exclude[i]);
break;
} catch (ClassNotFoundException e1) {
}
}
}
jsonConfig.setExcludes(getExcludeFieldsList(exclude));
String jsonString= JSONArray.fromObject(jsonList, jsonConfig).toString();
userlist.clear();
return jsonString;
}
/**
* 格式化Object对象,去掉无用的属性,并转换为json字符串

* @param object
*            object对象实例
* @param excludes
*            不包含在json字符串中的字段列表
* @return 格式化后的joson字符串
*/
public static String formatObjectWithExcludeFields(Object object,
String[] excludes) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
return JSONObject.fromObject(object, jsonConfig).toString();
}
/**
* 格式化Object列表对象,去掉无用的属性,并转换为json字符串

* @param object
*            object列表对象实例
* @param excludes
*            不包含在json字符串中的字段列表
* @return 格式化后的joson字符串
*/
public static String formatArrayObjectWithExcludeFields(Object object,
String[] excludes) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
return JSONArray.fromObject(object, jsonConfig).toString();
}
/**
* 扫描一个实体类中属性的get方法包含oneToMany,oneToOne,manyToMany,manyToOne注解的字段名称数组
* @param className  类全限定名字符串
* @return 返回该实体类中属性的get方法包含oneToMany,oneToOne,manyToMany,manyToOne注解的字段名称数组
*/
private static String[] getExcludeFields(String className) {
Set<String> list = new HashSet<String>();
list.add("handler");
list.add("hibernateLazyInitializer");
Field[] fields = null;
Class classes = null;
Method getMethod = null;
try {
classes = Class.forName(className);
} catch (Exception e) {
return list.toArray(new String[list.size()]);
}
fields = classes.getDeclaredFields();
for (Field field : fields) {
String firstLetter = field.getName().substring(0, 1).toUpperCase();
// 获得和属性对应的getXXX()方法的名字
String getMethodName = "get" + firstLetter
+ field.getName().substring(1);


// 获得和属性对应的getXXX()方法
try {
getMethod = classes.getMethod(getMethodName);
} catch (Exception e) {
System.out.print(e.getMessage());
}


if (oneManyJudge(getMethod)) {
list.add(field.getName());
}
}
list.add("class");
return list.toArray(new String[list.size()]);
}
/**
* 对一和多的关系进行判断,得到有相关注解的字段名称集合
* @param method  方法对象
* @return 返回判断结果,true为存在一对多的注解,false为不存在相关注解
*/
private static Boolean oneManyJudge(Method method){
Boolean result=false;
if (method!=null)
for(Class cls:(userlist.size()>0?userlist:list)){
if(method.getAnnotation(cls)!=null){
result=true;
break;
}
}
return result;
}
/**
* 初始化Json相应操作,用来设置Json相应时候的白名单类,包括OneToOne,OneToMany,ManyToOne,ManyToMany
* @param classType  OneToOne,OneToMany,ManyToOne,ManyToMany
*/
public static void initFilter(String[] classType){
if(classType!=null){
userlist.addAll(list);
for(String className:classType){
try {
Class cls=Class.forName("javax.persistence."+className);
userlist.remove(cls);
} catch (ClassNotFoundException e) {
System.out.print(e.getMessage());
}
}
}
}
/**
* 扫描一个实体类集合中属性的get方法包含oneToMany,oneToOne,manyToMany,manyToOne注解的字段名称数组
* @param className  类全限定名字符串集合
* @return 返回该实体类集合中属性的get方法包含oneToMany,oneToOne,manyToMany,manyToOne注解的字段名称数组
*/
private static String[] getExcludeFieldsList(String[] className) {
Set<String> list = new HashSet<String>();
list.add("handler");
list.add("hibernateLazyInitializer");
Field[] fields = null;
Class classes = null;
Method getMethod = null;
for (String cla : className) {
try {
classes = Class.forName(cla);
} catch (Exception e) {
continue;
}
fields = classes.getDeclaredFields();
for (Field field : fields) {
String firstLetter = field.getName().substring(0, 1)
.toUpperCase();
// 获得和属性对应的getXXX()方法的名字
String getMethodName = "get" + firstLetter
+ field.getName().substring(1);


// 获得和属性对应的getXXX()方法
try {
getMethod = classes.getMethod(getMethodName);
} catch (Exception e) {
System.out.println(e.getMessage());
}


if (oneManyJudge(getMethod)) {
list.add(field.getName());
}
}
}
list.add("class");
return list.toArray(new String[list.size()]);
}
public static void getDomainDir() {
String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath()+"com/domain";
File file=new File(path);
String []dir=null;
   if (file.isDirectory()){
       File[] fileLists = file.listFiles(); // 如果是目录,获取该目录下的内容集合
       dir=new String[fileLists.length];
       for (int i = 0; i < fileLists.length; i++) { // 循环遍历这个集合内容
        dir[i]=("com.domain."+fileLists[i].getName()+".");    //输出元素名称
       }
   }
   JsonUtils.setDirName(dir);
}
}
class DateJsonValueProcessor implements JsonBeanProcessor { 


public JSONObject processBean(Object bean, JsonConfig arg1) { 
JSONObject jsonObject = null; 
        if( bean instanceof java.sql.Date ){ 
             bean = new Date( ((java.sql.Date) bean).getTime() ); 
        } 
        if( bean instanceof java.sql.Timestamp ){ 
            bean = new Date( ((java.sql.Timestamp) bean).getTime() ); 
        } 
        if( bean instanceof Date ){ 
             jsonObject = new JSONObject(); 
             jsonObject.element("time", ( (Date) bean ).getTime()); 
        }else{ 
             jsonObject = new JSONObject( true ); 
        } 
          return jsonObject; 
       } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值