一、map对象
//json格式
String categoryName = " {"cateGoryName1": "瓷砖" , "cateGoryName2":"中板","cateGoryName3" : "大理石"} "
//map对象格式
{cateGoryName1=瓷砖 ,cateGoryName2=中板,cateGoryName3 =大理石}
import cn.hutool.json.JSONObject;
import org.json.JSONArray;
//解析分类
JSONObject jsonObject = new JSONObject(categoryName);
String cateGoryName1 = (String) jsonObject.get("cateGoryName1");
String cateGoryName2 = (String) jsonObject.get("cateGoryName2");
String cateGoryName3 = (String) jsonObject.get("cateGoryName3");
二、集合中的JSON转换
String goodsJson1 = " [{"goodsSpecs":"100X100","goodsFullSpecs":"大理石","goodsPrice0":"530","goodsSerial":"A1",
"bomSkuId":100003, "stockName":[{"stockName":"永川仓","goodsStorage":10}]
},{"goodsSpecs":"100X100","goodsFullSpecs":"大理石","goodsPrice0":"530","goodsSerial":"A1",
"bomSkuId":100003, "stockName":[{"stockName":"万州仓","goodsStorage":50}]
}] "
//创建一个新类来接受
public class GoodsJsonVo {
private int goodsId;
private String goodsSpecs;
private String goodsFullSpecs;
private String specValueIds;
private BigDecimal goodsPrice0;
private BigDecimal goodsPrice1;
private BigDecimal goodsPrice2;
private String goodsSerial;
private int colorId;
private String imageSrc;
private List<StockName> stockName = new ArrayList<StockName>();
}
第一种方式:
JSONArray index = new JSONArray(goodsJson1);
for (int i = 0; i < index.length(); i++) {
//拿到每一个值 分别设置到创建的对象中 再把该对应添加到list中 或者保存数据库 或者展示
GoodsJsonVo goodsJsonVo = new GoodsJsonVo();
goodsJsonVo.setGoodsSpecs((String) index2.getJSONObject(i).get("goodsSpecs"));
goodsJsonVo.setGoodsFullSpecs((String) index2.getJSONObject(i).get("goodsFullSpecs"));
String goodsPrice01 = (String) index2.getJSONObject(i).get("goodsPrice0");
BigDecimal goodsPrice0 = new BigDecimal(goodsPrice01);
goodsJsonVo.setGoodsPrice0(goodsPrice0);
goodsJsonVo.setGoodsSerial((String) index2.getJSONObject(i).get("goodsSerial"));
goodsJsonVo.setGoodsStorage(stockName.getGoodsStorage());
goodsJsonVo.setStockName(stockName.getStockName());
goodsJsonVo.setBomSkuId((Integer) index2.getJSONObject(i).get("bomSkuId"));
goodsJsonVoList.add(goodsJsonVo);
}
第二种方式:
// 调用下面的工具类
List<GoodsJsonNewVo> goodsJsonNewVo = JsonHelper.toGenericObject(goodsJson2, new TypeReference<List<GoodsJsonNewVo>>() {
});
三、 接口之间数据的转换
{
"code": 200,
"datas": {
"storeId": 57.0,
"SL": 10582,
"CSC": "主仓",
"materialType": "常规"
}
}
// 如何拿SL中的数据
HashMap<String, Object> map = new HashMap<>();
map.put("bomId",1 );
map.put("storeId",2);
map.put("materialType","常规" );
//post请求 第一种方式 调用下面的工具类
String postResult = httpHelper.httpPost("路径" , map)
JSONObject jsonObject = new JSONObject(postResult);
JSONObject jsonObject1 = (JSONObject)jsonObject.get("datas");
Integer goodsStorage = (Integer)jsonObject1.get("SL");
//post请求:第二种方式
import cn.hutool.http.HttpUtil;
HashMap<String, Object> postData = new HashMap(3);
postData.put("APP_PRIVATE_ID", "1");
postData.put("APP_PRIVATE_KEY", "2");
postData.put("memberid", 3);
String result = HttpUtil.post("访问路径", postData, 1500);
//get请求 调用 工具类
HashMap<String, Object> queryParams = new HashMap<>();
queryParams.put("recommendationCode", 123);
queryParams.put("memberId", 456);
String postResult = httpHelper.httpGet(url+"?"+ShopHelper.buildQueryString1(queryParams));
四、JsonHelper工具类类
package net.shopnc.common.util;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
/**
*
* JSON帮助类
*
* @author dqw
* Created 2017/4/17 13:37
*/
public class JsonHelper {
private static final Logger log = Logger.getLogger(JsonHelper.class);
final static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
}
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
/**
* JSON串转换为Java泛型对象
*
* @param <T>
* @param jsonString JSON字符串
* @param tr TypeReference,例如: new TypeReference< List<FamousUser> >(){}
* @return List对象列表
*/
public static <T> T toGenericObject(String jsonString, TypeReference<T> tr) {
if (jsonString == null || "".equals(jsonString)) {
return null;
} else {
try {
return (T) objectMapper.readValue(jsonString, tr);
} catch (Exception e) {
log.warn(jsonString);
log.warn("json error:" + e.getMessage());
}
}
return null;
}
/**
* Json字符串转Java对象
*
* @param jsonString
* @param c
* @return
*/
public static Object toObject(String jsonString, Class<?> c) {
if (jsonString == null || "".equals(jsonString)) {
return "";
} else {
try {
return objectMapper.readValue(jsonString, c);
} catch (Exception e) {
log.warn("json error:" + e.getMessage());
}
}
return null;
}
/**
* Java对象转Json字符串
*
* @param object Java对象,可以是对象,数组,List,Map等
* @return json 字符串
*/
public static String toJson(Object object) {
String jsonString = "";
try {
jsonString = objectMapper.writeValueAsString(object);
} catch (Exception e) {
log.warn("json error:" + e.getMessage());
}
return jsonString;
}
/**
* Json字符串转JsonNode
* @param jsonString
* @return
*/
public static JsonNode toJsonNode(String jsonString) {
try {
return objectMapper.readTree(jsonString);
} catch (IOException e) {
e.printStackTrace();
log.warn("json error:" + e.getMessage());
}
return null;
}
}
五、 HttpHelper工具类
package net.shopnc.common.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
*
* http帮助类
*
* @author dqw
* Created 2017/9/21 15:43
*/
@Component
public class HttpHelper {
private static final int DEFAULT_TIMEOUT = 3000;
private static final String DEFAULT_CHARSET = "utf-8";
private static final String CONTENT_TYPE_JSON = "application/json";
@Autowired
CloseableHttpClient httpClient;
/**
* http GET 请求
*
* @param url
* @return
* @throws Exception
*/
public String httpGet(String url) throws Exception {
return httpGet(url, DEFAULT_TIMEOUT, DEFAULT_CHARSET);
}
/**
* http GET 请求
*
* @param url
* @param timeout 超时时间
* @return
* @throws Exception
*/
public String httpGet(String url, int timeout) throws Exception {
return httpGet(url, timeout, DEFAULT_CHARSET);
}
/**
* http GET 请求
*
* @param url
* @param timeout 超时时间
* @param defaultCharset 编码例如UTF-8
* @return
* @throws Exception
*/
private String httpGet(String url, int timeout, String defaultCharset) throws Exception {
HttpGet httpGet = new HttpGet(url);
return httpRequest(httpGet, timeout, defaultCharset);
}
/**
* http POST 请求
*
* @param url
* @param params
* @return
* @throws Exception
*/
public String httpPost(String url, HashMap<String, Object> params) throws Exception {
java.util.List<NameValuePair> nvps = new ArrayList<>();
for (String key : params.keySet()) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
return httpPost(url, new UrlEncodedFormEntity(nvps, DEFAULT_CHARSET), DEFAULT_TIMEOUT);
}
/**
* http POST 请求
* @param url
* @param jsonParam
* @return
* @throws Exception
*/
public String httpPostJson(String url, String jsonParam) throws Exception {
StringEntity entityParam = new StringEntity(jsonParam.toString(), DEFAULT_CHARSET);
entityParam.setContentEncoding(DEFAULT_CHARSET);
entityParam.setContentType(CONTENT_TYPE_JSON);
return httpPost(url, entityParam, DEFAULT_TIMEOUT);
}
/**
* http POST 请求
* @param url
* @param entityParam
* @param timeout
* @return
* @throws Exception
*/
private String httpPost(String url, StringEntity entityParam, int timeout) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entityParam);
return httpRequest(httpPost, timeout, DEFAULT_CHARSET);
}
/**
* http 请求
* @param httpRequest
* @param timeout
* @param defaultCharset
* @return
* @throws Exception
*/
private String httpRequest(HttpRequestBase httpRequest, int timeout, String defaultCharset) throws Exception {
String result;
//设置最大请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpRequest.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpRequest);
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, defaultCharset);
EntityUtils.consume(entity);
} else {
throw new Exception(response.getStatusLine().toString());
}
} finally {
if (response != null) {
response.close();
}
}
return result;
}
}
六、 时间转换工具类
package net.shopnc.common.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
*
* 商城帮助类
*
* @author dqw
* Created 2017/4/17 13:40
*/
public class ShopHelper {
final static Logger logger = Logger.getLogger(ShopHelper.class);
/**
* 获取字符串md5
*
* @param str
* @return
*/
public static String getMd5(String str) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
logger.error(e.toString());
return str;
}
md.update(str.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
//convert the byte to hex format method 2
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
String hex = Integer.toHexString(0xff & byteData[i]);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
/**
* 生成随机令牌
*
* @return
*/
public static String getTokenCode() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
* 获取当前时间
*/
public static Timestamp getCurrentTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* 获取当前时间戳
*/
public static long getCurrentTime() {
return System.currentTimeMillis() / 1000;
}
/**
* 时间戳转换成日期格式字符串
*
* @param seconds 精确到秒的字符串
* @param formatStr
* @return
*/
public static Timestamp time2Timestamp(String seconds, String formatStr) {
if (seconds == null || seconds.length() <= 0) {
return null;
}
if (formatStr == null || formatStr.length() <= 0) {
formatStr = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
String timestampStr = sdf.format(new Date(Long.valueOf(seconds + "000")));
return Timestamp.valueOf(timestampStr);
}
/**
* 获取将来时间
*
* @param type Calendar.YEAR(年) Calendar.MONTH(月) Calendar.DATE(日)
* @param amount 数量,根据type的不同代表几年、几个月、几天
* @return
*/
public static Timestamp getFutureTimestamp(int type, int amount) {
Timestamp timestamp = ShopHelper.getCurrentTimestamp();
Calendar cal = Calendar.getInstance();
cal.setTime(timestamp);
cal.add(type, amount);
return new Timestamp(cal.getTime().getTime());
}
/**
* 获取将来时间
*
* @param time 需要添加的时间
* @param type Calendar.YEAR(年) Calendar.MONTH(月) Calendar.DATE(日) Calendar.SECOND(秒)
* @param amount 数量,根据type的不同代表几年、几个月、几天
* @return
*/
public static Timestamp getFutureTimestamp(Timestamp time, int type, int amount) {
Calendar cal = Calendar.getInstance();
cal.setTime(time);
cal.add(type, amount);
return new Timestamp(cal.getTime().getTime());
}
/**
* 获取一天的0点时间
*/
public static Timestamp getTimestampOfDayStart(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return Timestamp.valueOf(simpleDateFormat.format(time) + " 00:00:00");
}
/**
* 获取一天的23:59:59时间
*/
public static Timestamp getTimestampOfDayEnd(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return Timestamp.valueOf(simpleDateFormat.format(time) + " 23:59:59");
}
/**
* 获取一小时的:00:00时间
*/
public static Timestamp getTimestampOfHourStart(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
return Timestamp.valueOf(simpleDateFormat.format(time) + ":00:00");
}
/**
* 获取当前时间的小时HH
*/
public static String formatTimestampOfHour(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");
return simpleDateFormat.format(time);
}
/**
* 获取当前时间的年yyyy
*/
public static int formatTimestampOfYear(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.YEAR);
}
/**
* 获取当前时间的年MM
*/
public static int formatTimestampOfMonth(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 获取当前时间的天dd
*/
public static int formatTimestampOfDay(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.DATE);
}
/**
* 获取当前时间的yyyy-MM-dd格式
*/
public static String formatTimestamp() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(getCurrentTimestamp());
}
/**
* 获取当前时间的yyyy-MM-dd HH:mm:ss格式
*
* @return
*/
public static String formatTimestampHasS() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.format(getCurrentTimestamp());
}
/**
* 获取指定时间的yyyy-MM-dd HH:mm:ss格式
*
* @return
*/
public static String formatTimestampHasS(Timestamp time) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.format(time);
}
/**
* 字符串转时间戳
*
* @return
*/
public static Timestamp formatTimestampHasS(String time) {
if (time == null) {
return new Timestamp(0);
}
return Timestamp.valueOf(time);
}
/**
* 获取指定时间的yyyy-MM-dd HH:mm:ss格式
*/
public static String formatTimestamp(Timestamp time) {
if (time == null) {
time = getCurrentTimestamp();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(time);
}
/**
* 获取指定时间的yyyy-MM-dd HH:mm:ss格式
*/
public static String formatTimestamp(Timestamp time, String pattern) {
if (time == null) {
time = getCurrentTimestamp();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.format(time);
}
/**
* 计算时间戳相差秒数(time1-time2)
*/
public static long getTimestampSubOfSecond(Timestamp time1, Timestamp time2) {
return (time1.getTime() - time2.getTime())/1000;
}
/**
* 获取IP
*/
public static String getAddressIP() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return getAddressIP(request);
}
public static String getAddressIP(HttpServletRequest request) {
String ipAddress = null;
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
//Based on the IP network card in the machine configuration
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
//在通过多个代理的情况下,第一个真正的IP IP为客户,多个IP依照“,”分割,"***.***.***.***".length()
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
/**
* 拼接url参数
*
* @param params
* @return
* @throws Exception
*/
public static String buildQueryString(HashMap<String, String> params) {
String queryString = "";
try {
int i = 0;
for (String key : params.keySet()) {
queryString += (key + "=" + java.net.URLEncoder.encode(params.get(key), "utf-8"));
if (i < params.size() - 1) {
queryString += "&";
}
i++;
}
} catch (Exception e) {
}
return queryString;
}
/**
* 拼接url参数
*
* @param params
* @return
* @throws Exception
*/
public static String buildQueryString1(HashMap<String, Object> params) {
String queryString = "";
try {
int i = 0;
for (String key : params.keySet()) {
queryString += (key + "=" + java.net.URLEncoder.encode(params.get(key).toString(), "utf-8"));
if (i < params.size() - 1) {
queryString += "&";
}
i++;
}
} catch (Exception e) {
}
return queryString;
}
/**
* 字符串进行url编码
* @param str
* @return
*/
public static String getUrlEncodeString(String str) {
try{
str = java.net.URLEncoder.encode(str, "utf-8");
}catch (Exception e){
logger.info("ShopHelper->getUrlEncodeString异常为"+e.getMessage());
}
return str;
}
/**
* 转换逗号分隔的整形字符串为整形List
*
* @param idString 例:'1,2,3,4'
* @return
*/
public static List<Integer> convertIdStringToIntegerList(String idString) {
List<Integer> list = new ArrayList<>();
String[] stringArray = idString.split(",");
for (int i = 0; i < stringArray.length; i++) {
try {
list.add(Integer.valueOf(stringArray[i]));
} catch (NumberFormatException ex) {
continue;
}
}
return list;
}
/**
* 构造重定向跳转
* @param redirectUrl
* @return
*/
public static String buildRedirectString(String redirectUrl) {
if (StringUtils.isBlank(redirectUrl)) {
return "redirect:/";
}else{
return "redirect:" + redirectUrl;
}
}
}