jackson json和对象,集合的几种转换

jackson  json和对象,集合的几种转换

package com.crm.net.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

public class JsonUtils<T> {

	
	
	
	
	
//	ObjectMapper mapper2 = new ObjectMapper();
//	LoginInfo user = mapper2.readValue(result.toString(), LoginInfo.class);
//	System.out.println("user:" + user);
	
	/**
	 * 转换为 list
	 * 
	 * @param josn
	 * @param clz
	 * @return
	 */
	public List<T> jsonConverList(String josn, Class clz) {
		ObjectMapper jacksonMapper = new ObjectMapper();
		List<T> me = null;
		try {
			jacksonMapper
					.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
			// jacksonMapper.enableDefaultTyping();
			// jacksonMapper.setVisibility(JsonMethod.FIELD,JsonAutoDetect.Visibility.ANY);
			// jacksonMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
			// false);//格式化
			// jacksonMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
			// jacksonMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,
			// false);

			JavaType javaType = jacksonMapper.getTypeFactory()
					.constructParametricType(List.class, clz);// clz.selGenType().getClass()

			me = jacksonMapper.readValue(josn, javaType);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return me;
	}

	/**
	 * 转换对象里面有json
	 * 
	 * @param josn
	 * @param clz
	 * @return
	 */

	public T jsonConverObject(String josn, Class<T> clz) {

		T t = null;
		// ObjectMapper jacksonMapper = new ObjectMapper();
		InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(
				josn.getBytes()));
		BufferedReader streamReader = new BufferedReader(in);
		StringBuilder buff = new StringBuilder();
		String inputStr;
		try {
			while ((inputStr = streamReader.readLine()) != null)
				buff.append(inputStr);
			ObjectMapper mapper = new ObjectMapper();
			t = mapper.readValue(buff.toString(), clz);

		} catch (IOException e) {

			e.printStackTrace();
		}

		return t;
	}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。