json 工具类(Jackson)(对象,数组,List,Map,json串) 相互转换

json工具类功能

json 工具类(Jackson)(对象,数组,List,Map,json串) 相互转换_第1张图片

1、jsonObject 支持依赖Maven(springboot只需引入)

spring-boot-starter-web --> springmvc 自带 Jackson

 
            org.springframework.boot
            spring-boot-starter-web
 
        
  
	
	
		net.sf.json-lib
		json-lib
		2.4
		jdk15
	

2、JSON转换时间格式处理工具类

package com.example.utils_json.utils;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * TODO  json 时间转换
 *
 * @author 王松
 * @date 2019/8/22 18:08
 */
@SuppressWarnings("ALL")
public class DateJsonValueProcessor implements JsonValueProcessor {
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private DateFormat dateFormat;

    /**
     * 构造方法.
     *
     * @param datePattern 日期格式
     */
    public DateJsonValueProcessor(String datePattern) {
        try {
            dateFormat = new SimpleDateFormat(datePattern);
        } catch (Exception ex) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
        }
    }

    @Override
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    @Override
    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    private Object process(Object value) {
        if (value == null) {
            //为null时返回当前日期,也可以返回"",看需要
            value = new Date();
        }
        return dateFormat.format((Date) value);
    }

    public static String map2JSonStr(Map map) {
        JsonConfig jsonConfig = new JsonConfig();
        DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor(
                DEFAULT_DATE_PATTERN);
        jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
        JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);
        return jsonObject.toString();
    }


    /**
     * 将对象转换为json string,使用上面定义的的日期格式
     *
     * @param obj
     * @return
     */
    public static JSONObject obj2JsonObj(Object obj) {
        JsonConfig jsonConfig = new JsonConfig();
        DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor(
                DEFAULT_DATE_PATTERN);
        jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
        JSONObject jsonObject = JSONObject.fromObject(obj, jsonConfig);
        return jsonObject;
    }
}  

3、json 工具类

package com.example.utils_json.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import java.util.*;

@SuppressWarnings("ALL")
public class JsonUtil {


	/**
	 * TODO   返回json数据
     * @param null
	 * @date  2019/8/22 20:04
	 * @return
	 */
//	public static void jsonWrite(String json, HttpServletResponse response, Logger log) {
//		try {
//			response.setContentType("application/json; charset=UTF-8");
//			System.out.println("json数据" + json);
//			response.getWriter().write(json);
//			response.getWriter().flush();
//			response.getWriter().close();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			log.error("输出json用户数据错误");
//			log.error(e.getMessage());
//		}
//	}

	/**
	 * 从json对象字符格式中得到一个java对象
	 * @return
	 */
	public static Object getObjectJsonString(String jsonString, Class objclass) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Object obj = JSONObject.toBean(jsonObject, objclass);
		return obj;
	}

	/**
	 * 从json对象字符串格式中得到一个map对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Map getMapJson(String jsonString) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Iterator iter = jsonObject.keys();
		Object obj;
		Map valueMap = new HashMap();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			obj = jsonObject.get(key);
			valueMap.put(key, obj);
		}

		return valueMap;
	}

	/**
	 * 
	 * 从json对象字符串中获取一个object数组对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Object[] getObjectArrayJson(String jsonString) {
		JSONArray jsonarry = JSONArray.fromObject(jsonString);
		return jsonarry.toArray();
	}

	/**
	 * 从json对象字符串中获取一个list对象
	 * 
	 * @param jsonString
	 * @param jsonClass
	 * @return
	 */
	public static List getListJson(String jsonString) {
		JSONArray jsonarray = JSONArray.fromObject(jsonString);
		List valueList = new ArrayList();
		for (Object object : jsonarray) {
			valueList.add(object);
		}
		return valueList;
	}


	/**
	 * 从json对象字符串中获取N个list对象
	 *
	 * @param jsonString
	 * @param jsonClass
	 * @return
	 */
	public static List getListJson(String jsonString, Class jsonClass) {
		JSONArray jsonarray = JSONArray.fromObject(jsonString);
		Object obj;
		JSONObject jsonobject;
		List valueList = new ArrayList();
		for (Object object : jsonarray) {
			jsonobject = (JSONObject) object;
			obj = JSONObject.toBean(jsonobject, jsonClass);
			valueList.add(object);
		}
		return valueList;
	}


	/**
	 * 从json对象中获取字符串对象数组
	 * 
	 * @param jsonString
	 * @return
	 */
	public static String[] getStringArrayJson(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		String[] jsonStringArray = new String[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			jsonStringArray[i] = jsonArray.getString(i);
		}
		return jsonStringArray;
	}

	/**
	 * 将java类转换为json数据
	 * 
	 * @param obj
	 * @return
	 */
	public static String getJsonString(Object obj) {
		JSONObject jsonobject = null;
		try {
			JsonConfig jsonConfig = new JsonConfig();
			DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
			jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
			jsonobject = JSONObject.fromObject(obj, jsonConfig);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonobject.toString();

	}

	/**
	 * 将java数组数据转换为json数据
	 * 
	 * @param obj
	 * @return
	 */
	public static String getJsonString(Object[] obj) {
		JsonConfig jsonConfig = new JsonConfig();
		DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
		jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
		JSONArray jsonArray = JSONArray.fromObject(obj, jsonConfig);
		return jsonArray.toString();
	}

	/**
	 * 将list数据转换为json数据
	 * 
	 * @param list
	 * @return
	 */
	public static String getJsonString(List list) {
		JSONArray jsonArray = null;
		try {
			JsonConfig jsonConfig = new JsonConfig();
			DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
			jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
			jsonArray = JSONArray.fromObject(list, jsonConfig);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonArray.toString();
	}

	/**
	 * 将map数据转换为json数据
	 * 
	 * @param map
	 * @return
	 */
	public static String getJsonString(Map map) {
		JsonConfig jsonConfig = new JsonConfig();
		DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
		jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
		JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);
		return jsonObject.toString();
	}
}

 
  

4、测试代码

package com.example.utils_json.utils;

import com.example.utils_json.entity.User;

import java.util.*;

/**
 * @author wangsong
 * @date 2019/8/22
 */
public class Test {
    /**
     * 测试数组 --> 转json
     */
    public static void arrJson(){
        String[] arr = { "0", "0", "0", "0", "0", "0" };
        String jsonarr = JsonUtil.getJsonString(arr);
        System.out.println("测试数组 -->  转json  ===  " + jsonarr);
    }
    /**
     * 测试list--> 转json
     */
    public static void listJson(){
        List list = new ArrayList();
        list.add("张三");
        list.add(20);
        list.add(new Date());
        String jsonString = JsonUtil.getJsonString(list);
        System.out.println("测试list -->  转json  ===  " + jsonString);
    }
    /**
     * 测试map--> 转json
     */
    public static void mapJson(){
        Map map = new HashMap();
        map.put("1", "李四");
        map.put("2", 21);
        map.put("2", new Date());
        String jsonString1 = JsonUtil.getJsonString(map);
        System.out.println("测试map  -->  转json  ===  " + jsonString1);
    }
    /**
     * 测试对象-> 转json
     */
    public static void objJson(){
        User user = new User();
        user.setId(1);
        user.setName("王五");
        user.setPwd("6666");
        String jsonString = JsonUtil.getJsonString(user);
        System.out.println("测试对象 -->  转json  ===  " + jsonString);
    }
    /**
     * 测试json 转数组
     */
    public static void jsonArr(){
        String json = "[\"张三\",20,\"2019-06-15 11:18:19\"]";
        String[] stringArrayJson = JsonUtil.getStringArrayJson(json);
        System.out.println("测试json -->  转数组  ===  " + stringArrayJson.toString());
    }

    /**
     * 测试json 转List
     */
    public static void jsonList(){
        String json = "[\"张三\",20,\"2019-06-15 11:18:19\"]";
        List listJson = JsonUtil.getListJson(json);
        System.out.println("测试json -->  转List  ===  " + listJson);
    }

    /**
     * 测试json 转Map
     */
    public static void jsonMap(){
        String json = "{\"1\":\"李四\",\"2\":\"2019-06-15 11:18:19\"}";
        Map mapJson = JsonUtil.getMapJson(json);
        System.out.println("测试json -->  转map  ===  " + mapJson);
    }

    /**
     * 测试json字符串 转对象
     */
    public static void jsonObj(){
        String json = "{\"account\":\"\",\"id\":1,\"name\":\"王五\",\"pwd\":\"6666\",\"role_id\":0,\"the_id\":0}";
        User user = (User)JsonUtil.getObjectJsonString(json, User.class);
        System.out.println("测试json -->  转对象  ===  " + user);
    }



    public static void main(String[] args) {
        //json转
        jsonObj();    //json转对象
        jsonArr();    //json转数组
        jsonList();   //json转list
        jsonMap();    //json转map
        System.out.println("============================================");
        //转json
        objJson();    //对象转json
        arrJson();    //数组转json
        listJson();   //list转json
        mapJson();    //map转json
    }
}

 
  

User 类

package com.example.utils_json.entity;

import java.io.Serializable;

/**
 * @author wangsong
 * @date 2019/8/22
 */
public class User implements Serializable {

    private static final long serialVersionUID = -4265204478042445134L;
    private Integer id;

    private String name;

    private String pwd;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

}

测试打印结果

测试json -->  转对象  ===  com.example.utils_json.entity.User@1e643faf
测试json -->  转数组  ===  [Ljava.lang.String;@6e8dacdf
测试json -->  转List  ===  [张三, 20, 2019-06-15 11:18:19]
测试json -->  转map  ===  {1=李四, 2=2019-06-15 11:18:19}
============================================
测试对象 -->  转json  ===  {"id":1,"name":"王五","pwd":"6666"}
测试数组 -->  转json  ===  ["0","0","0","0","0","0"]
测试list -->  转json  ===  ["张三",20,"2019-08-22 20:14:28"]
测试map  -->  转json  ===  {"1":"李四","2":"2019-08-22 20:14:28"}

你可能感兴趣的:(#,json)