json工具类JsonUtil

package com.lgt.util;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.safein.webservice.page.ParamInfo;
import com.safein.webservice.util.MessageCode;

/**
 * josn处理类
 */
public class JsonUtil {
	private static final Logger logger = Logger.getLogger(JsonUtil.class);
	private final static ObjectMapper objectMapper = new ObjectMapper();
	static {
		objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
	}
	/**
	 * 格式化对象为json字符串
	 * @param obj
	 * @return
	 * @throws Exception
	 * @author julong
	 * @throws JsonProcessingException 
	 * @date 2016-6-23 上午11:23:56
	 */
	public static String formatObjectToJson(Object obj) throws JsonProcessingException{
		String result = null;
		logger.debug("【JsonUtil】格式化Object为string字符串操作");
		result = objectMapper.writeValueAsString(obj);
		return result;
	}
	/**
	 * 格式化对象为byte[]
	 * @param obj
	 * @return
	 * @throws Exception
	 * @throws JsonProcessingException 
	 */
	public static byte[] formatObjectToBytes(Object obj) throws JsonProcessingException{
		byte[] result = null;
		logger.debug("【JsonUtil】格式化Object为string字符串操作");
		result = objectMapper.writeValueAsBytes(obj);
		return result;
	}
	
	/**
	 * 格式化输入参数对象的方法
	 * @param data json字符串
	 * @return ParamInfo
	 * @throws JsonParseException json转换异常
	 * @throws JsonMappingException json映射异常
	 * @throws IOException io异常
	 */
	public static ParamInfo formatDataToBean(String data) throws JsonParseException, JsonMappingException, IOException{
		logger.debug("【JsonUtil】格式化string为ParamInfo操作");
		ParamInfo paramInfo = objectMapper.readValue(data, ParamInfo.class);
		return paramInfo;
	}
	
	/**
	 * 转换json字符串为Java对象
	 * @param data json字符串
	 * @return Object
	 * @throws JsonParseException json转换异常
	 * @throws JsonMappingException json映射异常
	 * @throws IOException io异常
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public static Object formatDataStrToObjectBean(String data,Class<?> c) throws JsonParseException, JsonMappingException, IOException {
		logger.debug("【JsonUtil】格式化string为JAVA BEAN 操作");
		return objectMapper.readValue(data, c);
	}
	
	
	/**
	 * 格式化参数为map对象的方法
	 * @param data
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> formatDataToMap(String data) throws JsonParseException, JsonMappingException, IOException{
		logger.debug("【JsonUtil】格式化string为Map操作");
		Map<String,Object> maps = objectMapper.readValue(data, Map.class);
		return maps;
	}
	

	/**
	 * 转换json为List<T> 对象
	 * @param data json数据
	 * @param clazz 需要转换的类
	 * @return <T> List<Object>
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static <T> List<T> formatDataToList(String data,Class<?> clazz) throws JsonParseException, JsonMappingException, IOException{
		logger.debug("【JsonUtil】格式化string为List<Object>操作");
		JavaType javaType  = objectMapper.getTypeFactory().constructParametricType(List.class, clazz);
		List<T> list = objectMapper.readValue(data, javaType);
		return list;
	}
	
	
	/**
	 * 格式化返回字符串json
	 * @param code 请求的参数
	 * @param errorCode 错误码
	 * @return String
	 */
	public static String formatResult(String code,String errorCode,String info){
		String result = "{\"rst\":\"{RESULT}\",\"msg\":\"{MESSAGE}\",\"data\":\"\",\"code\":\"{CODE}\",\"date\":\"{DATE}\",\"info\":\"{INFO}\"}";
		result = result.replace("{RESULT}", MessageCode.RESULT_FALSE);
		result = result.replace("{MESSAGE}", errorCode);
		result = result.replace("{CODE}", code);
		result = result.replace("{DATE}", DateUtil.getDateString());
		result = result.replace("{INFO}", info);
		return result;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
		String data = 	FileUtils.readFileToString(new File("D://apply.txt"));
		
		String str = JsonUtil.formatObjectToJson(data);
		
		System.out.println(str);
		JavaType javaType  = objectMapper.getTypeFactory().constructParametricType(List.class, Map.class);
		List<Object> list = objectMapper.readValue(data, javaType);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
//	String str = "{\"rst\":null,\"msg\":null,\"data\":null,\"code\":null,\"date\":null,\"page\":null,\"user\":null}";
//		System.out.println(str);
		
		
//		List<UserInfo> userList = new ArrayList<UserInfo>();
//		for (int i = 0; i < 6; i++) {
//			UserInfo user = new UserInfo();
//			user.setUserId("AAA"+i);
//			userList.add(user);
//		}
//		try {
//			String data = JsonUtil.formatObjectToJson(userList);
//			System.out.println(data);
//			
//			try {
//				ParamInfo paramInfo1 = JsonUtil.formatDataToBean(str);
//				//格式化为json
//				String json = JsonUtil.formatObjectToJson(paramInfo1.getData());
//				//json 格式化为map
//				Map<String,Object> maps = JsonUtil.formatDataToMap(json);
//				//Map<String, Object> map = JsonUtil.formatDataToMap(null);
//				System.out.println("---------------"+maps);
//				List<UserInfo> list = JsonUtil.formatDataToList(data, UserInfo.class);
//				for (int i = 0; i < list.size(); i++) {
//					System.out.println(list.get(i).getUserId());
//				}
//				
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		} catch (JsonProcessingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
//		UserInfo userInfo = new UserInfo();
		
		
		
//		System.out.println(JsonUtil.formatResult("1", "123", "1234"));
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值