JsonUtils.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, IllegalArgumentException,
   ParseException, IllegalAccessException, 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, 0, allMethods, 0, methods.length);
    System.arraycopy(superMethods, 0, allMethods, methods.length, superMethods.length);
    System.arraycopy(superSuperMethods, 0, allMethods, methods.length+superMethods.length, superSuperMethods.length);
    
   }else{
    allMethods=new Method[methods.length+superMethods.length];
    System.arraycopy(methods, 0, allMethods, 0, methods.length);
    System.arraycopy(superMethods, 0, allMethods, methods.length, 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, IllegalArgumentException,
   ParseException, IllegalAccessException, 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, IllegalArgumentException,
   ParseException, IllegalAccessException, 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(", ");
  }
  int end = buffer.lastIndexOf(",");
  String result;
  if (end > 0) {
   result = buffer.substring(0, 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);
  
 }

}

發佈了38 篇原創文章 · 獲贊 7 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章