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);
  
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
`jsonutils.tojsonstring` 是一个用于将对象转换为 JSON 字符串的方法。它通常用于将 Java 对象转换为 JSON 格式以进行数据传输或持久化存储。 使用 `jsonutils.tojsonstring` 方法,您需要按照以下步骤进行操作: 1. 导入相关的包: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; ``` 您需要确保已经正确导入了 FastJSON 库。 2. 创建一个对象并设置其属性: ```java public class ExampleObject { private String name; private int age; // 构造函数和 getter/setter 方法省略 // ... } ``` 在这个示例中,我们创建了一个名为 `ExampleObject` 的类,它具有 `name` 和 `age` 两个属性。 3. 使用 `jsonutils.tojsonstring` 方法将对象转换为 JSON 字符串: ```java ExampleObject obj = new ExampleObject(); obj.setName("Alice"); obj.setAge(25); String jsonString = JSON.toJSONString(obj, SerializerFeature.PrettyFormat); System.out.println(jsonString); ``` 在这个示例中,我们创建了一个 `ExampleObject` 的对象,并将其属性设置为 "Alice" 和 25。然后,我们使用 `JSON.toJSONString` 方法将对象转换为 JSON 字符串,并使用 `SerializerFeature.PrettyFormat` 参数使输出的 JSON 字符串具有良好的格式。 4. 运行代码并查看输出: ``` { "age": 25, "name": "Alice" } ``` 经过上述步骤,您将能够将对象转换为 JSON 字符串并输出。 请注意,上述示例中的 `jsonutils.tojsonstring` 方法是使用 FastJSON 库的方法,如果您使用的是其他 JSON 库,方法名称和用法可能会有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值