JSON处理工具

Jackson JSON处理工具类

====================================

jackson jar包依赖

<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.6</version>
 </dependency>

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Jackson JSON处理工具类
 * @author taiyang
 * @date 2016-05-05
 */
public class JsonMapper {

	private static final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
	
	private ObjectMapper mapper;

	public JsonMapper(Inclusion inclusion) {
		mapper = new ObjectMapper();		
		//允许json格式是单引号
		mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);		
		//设置输出包含的属性
        mapper.setSerializationInclusion(inclusion);
		//设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		//禁止使用int代表Enum的order()來反序列化Enum,非常危險
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
	}

	/**
	 * 创建输出全部属性到Json字符串的Binder.
	 */
	public static JsonMapper buildNormalBinder() {
		return new JsonMapper(Inclusion.ALWAYS);
	}

	/**
	 * 创建只输出非空属性到Json字符串的Binder.
	 */                     
	public static JsonMapper buildNonNullBinder() {
		return new JsonMapper(Inclusion.NON_NULL);
	}

	/**
	 * 创建只输出初始值被改变的属性到Json字符串的Binder.
	 */
	public static JsonMapper buildNonDefaultBinder() {
		return new JsonMapper(Inclusion.NON_DEFAULT);
	}
	
	//===========================================================
	
	/**
	 * Obj 2 Json
	 */
	public String Obj2Json(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			logger.error("Obj2Json error:{}--{}", object, e);
			return null;
		}
	}

	/**
	 * Json 2 Entity
	 */
	public <T> T Json2Entity(String jsonString, Class<T> clazz) {
		if(StringUtils.isEmpty(jsonString)) {
			return null;
		}
		try {
			return mapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			logger.error("Json2Entity error:{}--{}", jsonString, e);
			return null;
		}
	}

	/**
	 * Json 2 Collection(Map)
	 * 读取集合如List/Map
	 * List<MyBean> beanList = binder.getMapper().readValue(listString, new TypeReference<List<MyBean>>(){});
	 */
    public <T> T Json2Collection(String jsonString, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return mapper.readValue(jsonString, typeReference);
        } catch (Exception e) {
        	logger.error("Json2Collection error:{}--{}", jsonString, e);
            return null;
        }
    }
    
    /**
	 * 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数.
	 */
	public void setDateFormat(String pattern) {
		if (StringUtils.isNotBlank(pattern)) {
			SimpleDateFormat df = new SimpleDateFormat(pattern);
			mapper.getSerializationConfig().withDateFormat(df);
			mapper.getDeserializationConfig().withDateFormat(df);
			mapper.setDateFormat(df);
		}
	}
	
}
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.type.TypeReference;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 测试json
 */
public class TestJson {

	public static void main(String[] args) throws JSONException {
    	JsonMapper jm = JsonMapper.buildNormalBinder();
        
    	//1.Obj2Json
    	String jsonStr = jm.Obj2Json(new User());
        System.out.println(jsonStr);
        System.out.println("========================");
        
        //2.Json2Entity
        User user = jm.Json2Entity(jsonStr, User.class);
        System.out.println(user.getName() + "-" +user.getAge());
        System.out.println("========================");
        
        //3.Json2Collection
        User user1 = new User();
        User user2 = new User();
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);
        String jsonUserList = jm.Obj2Json(userList);
        List<User> userListJ = jm.Json2Collection(jsonUserList, new TypeReference<List<User>>(){});
        for(User u : userListJ){
        	System.out.println(u.getName());
        }
        System.out.println("========================");
        
        JSONObject jsonobj = new JSONObject(jsonStr);
        String name = jsonobj.getString("name");
        System.out.println(name);
	}
	
	static class User {
		int id = 1; 
		String name = "taiyang";
		int age = 26;
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
	}
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值