常用工具类

1、Json、String、Map相互转换工具类

Mave依赖

        
            com.squareup.okhttp3
            okhttp
            provided
        
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Jackson 工具类
 * 

Title: MapperUtils

*

Description:

* * @author linke * @version 1.0.0 * @date 2018/3/4 21:50 */ public class MapperUtils { private final static ObjectMapper objectMapper = new ObjectMapper(); public static ObjectMapper getInstance() { return objectMapper; } /** * 转换为 JSON 字符串 * * @param obj * @return * @throws Exception */ public static String obj2json(Object obj) throws Exception { return objectMapper.writeValueAsString(obj); } /** * 转换为 JSON 字符串,忽略空值 * * @param obj * @return * @throws Exception */ public static String obj2jsonIgnoreNull(Object obj) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.writeValueAsString(obj); } /** * 转换为 JavaBean * * @param jsonString * @param clazz * @return * @throws Exception */ public static T json2pojo(String jsonString, Class clazz) throws Exception { objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); return objectMapper.readValue(jsonString, clazz); } /** * 字符串转换为 Map * * @param jsonString * @return * @throws Exception */ public static Map json2map(String jsonString) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.readValue(jsonString, Map.class); } /** * 字符串转换为 Map */ public static Map json2map(String jsonString, Class clazz) throws Exception { Map> map = objectMapper.readValue(jsonString, new TypeReference>() { }); Map result = new HashMap(); for (Map.Entry> entry : map.entrySet()) { result.put(entry.getKey(), map2pojo(entry.getValue(), clazz)); } return result; } /** * 深度转换 JSON 成 Map * * @param json * @return */ public static Map json2mapDeeply(String json) throws Exception { return json2MapRecursion(json, objectMapper); } /** * 把 JSON 解析成 List,如果 List 内部的元素存在 jsonString,继续解析 * * @param json * @param mapper 解析工具 * @return * @throws Exception */ private static List json2ListRecursion(String json, ObjectMapper mapper) throws Exception { if (json == null) { return null; } List list = mapper.readValue(json, List.class); for (Object obj : list) { if (obj != null && obj instanceof String) { String str = (String) obj; if (str.startsWith("[")) { obj = json2ListRecursion(str, mapper); } else if (obj.toString().startsWith("{")) { obj = json2MapRecursion(str, mapper); } } } return list; } /** * 把 JSON 解析成 Map,如果 Map 内部的 Value 存在 jsonString,继续解析 * * @param json * @param mapper * @return * @throws Exception */ private static Map json2MapRecursion(String json, ObjectMapper mapper) throws Exception { if (json == null) { return null; } Map map = mapper.readValue(json, Map.class); for (Map.Entry entry : map.entrySet()) { Object obj = entry.getValue(); if (obj != null && obj instanceof String) { String str = ((String) obj); if (str.startsWith("[")) { List list = json2ListRecursion(str, mapper); map.put(entry.getKey(), list); } else if (str.startsWith("{")) { Map mapRecursion = json2MapRecursion(str, mapper); map.put(entry.getKey(), mapRecursion); } } } return map; } /** * 将 JSON 数组转换为集合 * * @param jsonArrayStr * @param clazz * @return * @throws Exception */ public static List json2list(String jsonArrayStr, Class clazz) throws Exception { JavaType javaType = getCollectionType(ArrayList.class, clazz); List list = (List) objectMapper.readValue(jsonArrayStr, javaType); return list; } /** * 获取泛型的 Collection Type * * @param collectionClass 泛型的Collection * @param elementClasses 元素类 * @return JavaType Java类型 * @since 1.0 */ public static JavaType getCollectionType(Class collectionClass, Class... elementClasses) { return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } /** * 将 Map 转换为 JavaBean * * @param map * @param clazz * @return */ public static T map2pojo(Map map, Class clazz) { return objectMapper.convertValue(map, clazz); } /** * 将 Map 转换为 JSON * * @param map * @return */ public static String mapToJson(Map map) { try { return objectMapper.writeValueAsString(map); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 将 JSON 对象转换为 JavaBean * * @param obj * @param clazz * @return */ public static T obj2pojo(Object obj, Class clazz) { return objectMapper.convertValue(obj, clazz); } /** * 将指定节点的 JSON 数据转换为 JavaBean * * @param jsonString * @param clazz * @return * @throws Exception */ public static T json2pojoByTree(String jsonString, String treeNode, Class clazz) throws Exception { JsonNode jsonNode = objectMapper.readTree(jsonString); JsonNode data = jsonNode.findPath(treeNode); return json2pojo(data.toString(), clazz); } /** * 将指定节点的 JSON 数组转换为集合 * * @param jsonStr JSON 字符串 * @param treeNode 查找 JSON 中的节点 * @return * @throws Exception */ public static List json2listByTree(String jsonStr, String treeNode, Class clazz) throws Exception { JsonNode jsonNode = objectMapper.readTree(jsonStr); JsonNode data = jsonNode.findPath(treeNode); return json2list(data.toString(), clazz); } }

2、Http请求-OkHttp工具类

Maven依赖:

        
            com.fasterxml.jackson.core
            jackson-databind
            provided
        
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * OKHttp3
 * 

* Description: *

* * @author linke * @version v1.0.0 * @date 2019-07-29 14:05:08 * @see com.lingkang.myshop.plus.commons.utils */ public class OkHttpClientUtil { private static final int READ_TIMEOUT = 100; private static final int CONNECT_TIMEOUT = 60; private static final int WRITE_TIMEOUT = 60; private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final byte[] LOCKER = new byte[0]; private static OkHttpClientUtil mInstance; private OkHttpClient okHttpClient; private OkHttpClientUtil() { okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder(); // 读取超时 clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS); // 连接超时 clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS); //写入超时 clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS); okHttpClient = clientBuilder.build(); } /** * 单例模式获取 NetUtils * * @return {@link OkHttpClientUtil} */ public static OkHttpClientUtil getInstance() { if (mInstance == null) { synchronized (LOCKER) { if (mInstance == null) { mInstance = new OkHttpClientUtil(); } } } return mInstance; } /** * GET,同步方式,获取网络数据 * * @param url 请求地址 * @return {@link Response} */ public Response getData(String url) { // 构造 Request Request.Builder builder = new Request.Builder(); Request request = builder.get().url(url).build(); // 将 Request 封装为 Call Call call = okHttpClient.newCall(request); // 执行 Call,得到 Response Response response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } return response; } /** * POST 请求,同步方式,提交数据 * * @param url 请求地址 * @param bodyParams 请求参数 * @return {@link Response} */ public Response postData(String url, Map bodyParams) { // 构造 RequestBody RequestBody body = setRequestBody(bodyParams); // 构造 Request Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.post(body).url(url).build(); // 将 Request 封装为 Call Call call = okHttpClient.newCall(request); // 执行 Call,得到 Response Response response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } return response; } /** * GET 请求,异步方式,获取网络数据 * * @param url 请求地址 * @param myNetCall 回调函数 */ public void getDataAsync(String url, final MyNetCall myNetCall) { // 构造 Request Request.Builder builder = new Request.Builder(); Request request = builder.get().url(url).build(); // 将 Request 封装为 Call Call call = okHttpClient.newCall(request); // 执行 Call call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { myNetCall.failed(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { myNetCall.success(call, response); } }); } /** * POST 请求,异步方式,提交数据 * * @param url 请求地址 * @param bodyParams 请求参数 * @param myNetCall 回调函数 */ public void postDataAsync(String url, Map bodyParams, final MyNetCall myNetCall) { // 构造 RequestBody RequestBody body = setRequestBody(bodyParams); // 构造 Request buildRequest(url, myNetCall, body); } /** * 同步 POST 请求,使用 JSON 格式作为参数 * * @param url 请求地址 * @param json JSON 格式参数 * @return 响应结果 * @throws IOException 异常 */ public String postJson(String url, String json) throws IOException { RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } /** * 异步 POST 请求,使用 JSON 格式作为参数 * * @param url 请求地址 * @param json JSON 格式参数 * @param myNetCall 回调函数 * @throws IOException 异常 */ public void postJsonAsync(String url, String json, final MyNetCall myNetCall) throws IOException { RequestBody body = RequestBody.create(json, JSON); // 构造 Request buildRequest(url, myNetCall, body); } /** * 构造 POST 请求参数 * * @param bodyParams 请求参数 * @return {@link RequestBody} */ private RequestBody setRequestBody(Map bodyParams) { RequestBody body = null; okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder(); if (bodyParams != null) { Iterator iterator = bodyParams.keySet().iterator(); String key = ""; while (iterator.hasNext()) { key = iterator.next().toString(); formEncodingBuilder.add(key, bodyParams.get(key)); } } body = formEncodingBuilder.build(); return body; } /** * 构造 Request 发起异步请求 * * @param url 请求地址 * @param myNetCall 回调函数 * @param body {@link RequestBody} */ private void buildRequest(String url, MyNetCall myNetCall, RequestBody body) { Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.post(body).url(url).build(); // 将 Request 封装为 Call Call call = okHttpClient.newCall(request); // 执行 Call call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { myNetCall.failed(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { myNetCall.success(call, response); } }); } /** * 自定义网络回调接口 */ public interface MyNetCall { /** * 请求成功的回调处理 * * @param call {@link Call} * @param response {@link Response} * @throws IOException 异常 */ void success(Call call, Response response) throws IOException; /** * 请求失败的回调处理 * * @param call {@link Call} * @param e 异常 */ void failed(Call call, IOException e); } }

3、微服务result工具类

通用数据传输对象

import lombok.Data;

import java.io.Serializable;

/**
 * 通用数据传输对象
 * 

* Description: *

* * @author linke * @version v1.0.0 * @date 2019-07-26 04:43:54 * @see com.lingkang.myshop.plus.commons.dto */ @Data public class ResponseResult implements Serializable { private static final long serialVersionUID = 3468352004150968551L; /** * 状态码 */ private Integer code; /** * 消息 */ private String message; /** * 返回对象 */ private T data; public ResponseResult() { super(); } public ResponseResult(Integer code) { super(); this.code = code; } public ResponseResult(Integer code, String message) { super(); this.code = code; this.message = message; } public ResponseResult(Integer code, Throwable throwable) { super(); this.code = code; this.message = throwable.getMessage(); } public ResponseResult(Integer code, T data) { super(); this.code = code; this.data = data; } public ResponseResult(Integer code, String message, T data) { super(); this.code = code; this.message = message; this.data = data; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + ((message == null) ? 0 : message.hashCode()); result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ResponseResult other = (ResponseResult) obj; if (data == null) { if (other.data != null) { return false; } } else if (!data.equals(other.data)) { return false; } if (message == null) { if (other.message != null) { return false; } } else if (!message.equals(other.message)) { return false; } if (code == null) { if (other.code != null) { return false; } } else if (!code.equals(other.code)) { return false; } return true; } /** * 通用状态码 *

* Description: *

* * @author Lusifer * @version v1.0.0 * @date 2019-07-30 05:02:49 * @see com.funtl.myshop.plus.commons.dto */ public class CodeStatus { /** * 请求成功 */ public static final int OK = 20000; /** * 请求失败 */ public static final int FAIL = 20002; /** * 非法请求 */ public static final int ILLEGAL_REQUEST = 50000; /** * 非法令牌 */ public static final int ILLEGAL_TOKEN = 50008; /** * 其他客户登录 */ public static final int OTHER_CLIENTS_LOGGED_IN = 50012; /** * 令牌已过期 */ public static final int TOKEN_EXPIRED = 50014; } }

你可能感兴趣的:(常用工具类)