加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JsonUtils.java

发布时间:2020-12-16 19:56:10 所属栏目:百科 来源:网络整理
导读:package com.gdcn.bjxy.common.helper; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.

package com.gdcn.bjxy.common.helper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONValue;
import java.lang.System;
import java.math.BigDecimal;

public class JsonUtils {

/**
* Map a POJO to the JSON representation
* @param obj 需要转换的对象
* @return JSON
*/
public static String objectToJson(Object obj) {
try {
JSONValue value = JSONMapper.toJSON(obj);
//Convert the JSON value into a string representation
return value.render(true);
} catch (MapperException e) {
e.printStackTrace();
}
return null;
}

/**
* 将制定对象转换为Json字符
* @param o
* @return
* @throws UnsupportedEncodingException
* @throws ParseException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String toJson(Object o) throws UnsupportedEncodingException,
ParseException,IllegalArgumentException,IllegalAccessException,
InvocationTargetException {
if(null==o){
return "";
}

//支持的基本数据类型
if (isSupport(o.getClass())) {
return convert(o,o.getClass()).toString();
//是否是集合类型
} else if (o instanceof Collection || o.getClass().isArray()) {
return toJsonArray(o);
//是否是Map类型
} else if (o instanceof Map) {
return toJsonMap(o);
//其他POJO对象
} else {
return toJsonObject(o);
}
}

/**
* 将指定POJO对象转换为Json
* @param o
* @return
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException
* @throws ParseException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String toJsonObject(Object o)
throws UnsupportedEncodingException,InvocationTargetException {

if (o == null) {
return "";
}
Class<?> clazz = o.getClass();

/**
* 根据项目实际情况,只查找2级父类
*/
Class<?> superClazz =clazz.getSuperclass();
Method[] superMethods=null;
Method[] superSuperMethods=null;

if(null!=superClazz && !superClazz.getSimpleName().equals("Object") && !superClazz.getSimpleName().equals("ActionForm")){
superMethods=superClazz.getDeclaredMethods();

Class<?> superSuperClazz =superClazz.getSuperclass();
if(null!=superSuperClazz ){
superSuperMethods=superSuperClazz.getDeclaredMethods();
}
}
//获取当前对象所有的方法
Method[] methods = clazz.getDeclaredMethods();
//对象所有的方法,包括2级父类
Method[] allMethods=null;

if((null!=superMethods && superMethods.length>0)||(null!=superSuperMethods && superSuperMethods.length>0)){

if(null!=superSuperMethods && superSuperMethods.length>0){
allMethods=new Method[methods.length+superMethods.length+superSuperMethods.length];
System.arraycopy(methods,allMethods,methods.length);
System.arraycopy(superMethods,methods.length,superMethods.length);
System.arraycopy(superSuperMethods,methods.length+superMethods.length,superSuperMethods.length);

}else{
allMethods=new Method[methods.length+superMethods.length];
System.arraycopy(methods,superMethods.length);
allMethods=new Method[methods.length+superMethods.length];
}

}else{
allMethods=methods;
}

//获取对象所有以get开头的方法
Method[] getMethods = BeanHelper.methodStartWithGet(allMethods);
StringBuffer buffer = new StringBuffer();
//字段名
String key;
//字段值
Object value;
buffer.append("{");
for (Method method : getMethods) {
key = StringUtils.changFirstCharacterCase(method.getName().substring(3),false);
buffer.append(key);
if("class".equals(key)) {
continue;
}

buffer.append(": ");
value=null;
if(null!=method){
try{
value = method.invoke(o);
}
catch(Exception exp){
value=null;
}
}
if (value == null) {
buffer.append("''");
} else if (isSupport(method.getReturnType())) {
buffer.append(convert(value,method.getReturnType()));
} else if (value instanceof Collection
|| value.getClass().isArray()) {
buffer.append(toJsonArray(value));
} else{
buffer.append("''");
}
buffer.append(",");
}
int end = buffer.lastIndexOf(",");
//返回Json结果
String result;
if (end > 0) {
result = buffer.substring(0,end) + "}";
} else {
result = buffer.toString() + "}";
}
return result;

}

/**
* 将指定对象转换为Json数组
* @param o
* @return
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException
* @throws ParseException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String toJsonArray(Object o)
throws UnsupportedEncodingException,InvocationTargetException {
if (o == null) {
return "";
}
StringBuffer buffer = new StringBuffer();
buffer.append("[");
if (o instanceof Collection) {
Collection<?> temp = (Collection<?>) o;
for (Object oo : temp) {
buffer.append(toJson(oo));
buffer.append(",");
}
} else if (o.getClass().isArray()) {
int arrayLength = Array.getLength(o);
for (int i = 0; i < arrayLength; i++) {
Object oo = Array.get(o,i);
buffer.append(toJson(oo));
buffer.append(",");
}
}
int end = buffer.lastIndexOf(",");
String result;
if (end > 0) {
result = buffer.substring(0,end) + "]";
} else {
result = buffer.toString() + "]";
}
return result;
}

/**
* 将指定map对象转换为Json
* @param o
* @return
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException
* @throws ParseException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String toJsonMap(Object o)
throws UnsupportedEncodingException,InvocationTargetException {
if (o == null) {
return "";
}
StringBuffer buffer = new StringBuffer();
buffer.append("{");
Map<?,?> temp = (Map<?,?>) o;
for (Object oo : temp.keySet()) {
buffer.append(toJson(oo));
buffer.append(": ");
buffer.append(toJson(temp.get(oo)));
buffer.append(",end) + "}";
} else {
result = buffer.toString() + "}";
}
return result;
}

/**
* 数据转换,将数据转换为指定类型的数据
* @param o
* @param clazz
* @return
* @throws UnsupportedEncodingException
* @throws ParseException
*/

public static Object convert(Object o,Class<?> clazz)
throws UnsupportedEncodingException,ParseException {


String value = o.toString();
if (clazz.equals(String.class))
return "'" + value + "'";
if (clazz.equals(int.class) || clazz.equals(Integer.class))
return Integer.valueOf(value);
if (clazz.equals(boolean.class) || clazz.equals(Boolean.class))
return Boolean.valueOf(value);
if (clazz.equals(long.class) || clazz.equals(Long.class))
return Long.valueOf(value);
if (clazz.equals(float.class) || clazz.equals(Float.class))
return Float.valueOf(value);
if (clazz.equals(double.class) || clazz.equals(Double.class))
return Double.valueOf(value);
if (clazz.equals(short.class) || clazz.equals(Short.class))
return Short.valueOf(value);
if (clazz.equals(byte.class) || clazz.equals(Byte.class))
return Byte.valueOf(value);
if (clazz.equals(BigDecimal.class))
return "'" + value.toString() + "'";

if (value.length() > 0 && clazz.equals(char.class)
|| clazz.equals(Character.class))
return value.charAt(0);
if (clazz.equals(Date.class))
return "'" + new SimpleDateFormat("yyyy-MM-dd").format(o) + "'";
if (clazz.equals(Timestamp.class))
return new Timestamp(new SimpleDateFormat("yyyy-MM-dd")
.parse(value).getTime());
throw new IllegalArgumentException("Cannot convert to type: "
+ clazz.getName());
}

public static boolean isSupport(Class<?> clazz) {
return supportedClasses.contains(clazz);
}

/**
* 将对象输出为Json格式数据
* @param response
* @param Object
*/
public static void writeJson(HttpServletResponse response,Object Object) {
response.setContentType("text/text;charset=UTF-8");
response.setHeader("Charset","UTF-8");
String result = "";
try {
result = toJson(Object);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
try {
response.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}

private static Set<Class<?>> supportedClasses = new HashSet<Class<?>>();

static {
supportedClasses.add(boolean.class);
supportedClasses.add(char.class);
supportedClasses.add(byte.class);
supportedClasses.add(short.class);
supportedClasses.add(int.class);
supportedClasses.add(long.class);
supportedClasses.add(float.class);
supportedClasses.add(double.class);
supportedClasses.add(Boolean.class);
supportedClasses.add(Character.class);
supportedClasses.add(Byte.class);
supportedClasses.add(Short.class);
supportedClasses.add(Integer.class);
supportedClasses.add(Long.class);
supportedClasses.add(Float.class);
supportedClasses.add(Double.class);
supportedClasses.add(String.class);
supportedClasses.add(Date.class);
supportedClasses.add(Timestamp.class);
supportedClasses.add(BigDecimal.class);

}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读