json字符串转list对象

2018-10-29  本文已影响14人  愤怒的_菜鸟
String serverUrl = PathUtils.zqBaseUrl + "/theme/getFinishedList.do?";
String params = "type=" + type;
String result = "";
result = HttpUtil.getRequestPost(serverUrl, params);//json字符串
List<CbxyCell_temporary> list = new ArrayList <CbxyCell_temporary();  
list=JsonUtil.toObject(result,new TypeReference<List<CbxyCell_temporary>>()  { });
json工具类
package net.radar.util;

import java.io.IOException;

import net.radar.entity.LightEquipment;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JsonUtil {
    
    
    private static final String JACKSON_OBJECT_MAPPER_BEAN_NAME = "jacksonObjectMapper";// jackson ObjectMapper Bean名称

    public static ObjectMapper getMapper() {
        return (ObjectMapper) SpringUtil.getBean(JACKSON_OBJECT_MAPPER_BEAN_NAME);
    }
    
    // 将对象转换为JSON字符串
    public static String toJson(Object object) {
        ObjectMapper mapper = getMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // 将JSON字符串转换为对象
    public static <T> T toObject(String json, Class<T> clazz) {
        ObjectMapper mapper = getMapper();
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // 将JSON字符串转换为对象
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static <T> T toObject(String json, TypeReference typeReference) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = getMapper();
        return mapper.readValue(json, typeReference);
    }

}
上一篇下一篇

猜你喜欢

热点阅读