JSON处理工具类 Java中JSON处理工具类使用详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JSON处理工具类 Java中JSON处理工具类使用详解

御前提笔小书童   2021-03-28 我要评论
想了解Java中JSON处理工具类使用详解的相关内容吗,御前提笔小书童在本文为您仔细讲解JSON处理工具类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,JSON,工具类,下面大家一起来学习吧。

import java.io.IOException; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletResponse; 
 
import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.serializer.SerializerFeature; 
 
/** 
 * 
 * @author humf 
 * 
 */ 
public class FastJsonUtil { 
   
  /** 
   * 将对象转成json串 
   * @param object 
   * @return 
   */ 
  public static String toJSONString(Object object){ 
    //DisableCircularReferenceDetect来禁止循环引用检测 
    return JSON.toJSONString(object,SerializerFeature.DisableCircularReferenceDetect); 
  } 
   
  //输出json 
  public static void write_json(HttpServletResponse response,String jsonString){ 
    response.setContentType("application/json;utf-8"); 
    response.setCharacterEncoding("UTF-8"); 
    try { 
      response.getWriter().print(jsonString); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    }   
  } 
   
  /** 
   * ajax提交后回调的json字符串 
   * @return 
   */ 
  public static String ajaxResult(boolean success,String message) 
  { 
    Map map=new HashMap(); 
    map.put("success", success);//是否成功 
    map.put("message", message);//文本消息 
    String json= JSON.toJSONString(map);     
    return json; 
  } 
   
 
  /** 
   * JSON串自动加前缀 
   * @param json 原json字符串 
   * @param prefix 前缀 
   * @return 加前缀后的字符串 
   */ 
 
  public static String JsonFormatterAddPrefix(String json,String prefix,Map<String,Object> newmap) 
  { 
    if(newmap == null){ 
      newmap = new HashMap(); 
    } 
    Map<String,Object> map = (Map) JSON.parse(json); 
 
    for(String key:map.keySet()) 
    { 
      Object object=map.get(key); 
      if(isEntity(object)){ 
        String jsonString = JSON.toJSONString(object); 
        JsonFormatterAddPrefix(jsonString,prefix+key+".",newmap); 
         
      }else{ 
        newmap.put(prefix+key, object); 
      } 
       
    } 
    return JSON.toJSONString(newmap);     
  } 
  /** 
   * 判断某对象是不是实体 
   * @param object 
   * @return 
   */ 
  private static boolean isEntity(Object object) 
  { 
    if(object instanceof String ) 
    { 
      return false; 
    } 
    if(object instanceof Integer ) 
    { 
      return false; 
    } 
    if(object instanceof Long ) 
    { 
      return false; 
    } 
    if(object instanceof java.math.BigDecimal ) 
    { 
      return false; 
    } 
    if(object instanceof Date ) 
    { 
      return false; 
    } 
    if(object instanceof java.util.Collection ) 
    { 
      return false; 
    } 
    return true; 
     
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们