Java常见帮助类(6)JSON帮助类

大家常用的一个帮组类:

/**
 * Json工具类
 * 
 * @author 
 * 
 */
public class JsonUtil
{
    private static Logger logger = Logger.getLogger(JsonUtil.class);
    
    /**
    * 用fastjson 将json字符串解析为一个 JavaBean
    * 
    * @param jsonString
    * @param cls
    * @return
    */
    public static  T parseBean(String jsonString, Class cls)
    {
        T t = null;
        try
        {
            t = JSON.parseObject(jsonString, cls);
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return t;
    }
    
    /**
    * 用fastjson 将json字符串 解析成为一个 List 及 List
    * 
    * @param jsonString
    * @param cls
    * @return
    */
    public static  List parseBeanArray(String jsonString, Class cls)
    {
        List list = new ArrayList();
        try
        {
            list = JSON.parseArray(jsonString, cls);
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
        return list;
    }
    
    /**
    * 用fastjson 将jsonString 解析成 List>
    * 
    * @param jsonString
    * @return
    */
    public static List> parseListMap(String jsonString)
    {
        List> list = new ArrayList>();
        try
        {
            // 两种写法
            // list = JSON.parseObject(jsonString, new
            // TypeReference>>(){}.getType());
            
            list = JSON.parseObject(jsonString, new TypeReference>>()
            {
            });
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
        return list;
    }
    
    /**
    * 用fastjson 将Object 转化为jsonString
    * 
    * @param object
    * @return
    */
    public static String toJsonString(Object object)
    {
        String jsonString = "";
        try
        {
            jsonString = JSON.toJSONString(object);
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return jsonString;
    }
    
    public static void main(String[] args)
    {
        
        String strResult = "[{\"result_message\":\"返回扫描结果\",\"taskResultId\":608328,\"result_vulMiddle\":0,\"result_endTime\":\"\",\"result_returnCode\":0,\"result_vulSum\":0,\"domain\":\"gaokao.haedu.gov.cn\",\"result_vulLow\":0,\"info_message\":\"成功创建任务\",\"result_vulHigh\":0,\"info_returnCode\":0,\"result_startTime\":\"2016-07-11 11:28:03\"}]";
        List> resultlist = new ArrayList>();
        resultlist = JsonUtil.parseListMap(strResult);
        System.out.println(resultlist);
        System.out.println(resultlist.get(0).get("taskResultId"));
    }
}


你可能感兴趣的:(Java常用帮助类)