当前位置:网站首页>JSON转换工具类
JSON转换工具类
2022-07-02 23:04:00 【'LYong】
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
/**
*
* ClassName: JsonUtils.java <br>
* Description:json 工具类 <br>
* Create by: name:luyong <br>email: 15701203325@163.com
*/
public class JsonUtils {
/**
* 默认日期格式
*/
private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static ObjectMapper defaultObjectMapper = getObjectMapper(null);
/**
* 返回一个Object对象
* @param datePattern,指定能够处理的日期字符串格式,如果没有指定默认为yyyy-MM-dd HH:mm:ss
* @return
*/
public static ObjectMapper getObjectMapper(String datePattern) {
if (StringUtils.isBlank(datePattern)) {
datePattern = DATE_PATTERN;
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat(datePattern));
//允许字段名字不使用引号
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
//允许单引号
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 忽略未识别的参数(解决json串中多属性,而类中又未定义的情况)
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//将对象转换成string时,json的key是否按照对象的field的自然顺序排列
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, false);
return objectMapper;
}
/**
* 将规定对象转换成json字符串。日期类型按照 yyyy-MM-dd HH:mm:ss 的格式转换成字符串
* @param obj 对象
* @return json字符串
*/
public static String writeValueAsString(Object obj){
try {
return getObjectMapper(null).writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将规定对象转换成json字符串
* @param object
* @param datePattern 指定转换后的日期格式
* @return
*/
public static String writeValueAsString(Object object, String datePattern) {
try {
return getObjectMapper(datePattern).writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将规定对象转换成json字符串
* @param object
* @param datePattern 指定转换后的日期格式
* @param indentOutput 缩进输出
* @return
*/
public static String writeValueAsString(Object object, String datePattern,boolean indentOutput) {
try {
ObjectMapper objectMapper = getObjectMapper(datePattern);
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将json字符串转为对象
* @param <T> 返回类型
* @param content json字符串
* @param valueType 返回类型
* @return 对象
*/
public static <T> T readValue(String content, Class<T> valueType) {
try {
ObjectMapper objectMapper = getObjectMapper(null);
return objectMapper.readValue(content, valueType);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将json转换成对象
* @param content
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String content, TypeReference<T> valueTypeRef){
try {
ObjectMapper objectMapper = getObjectMapper(null);
return objectMapper.readValue(content, valueTypeRef);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将json转换成对象
* @param content
* @param valueTypeRef
* @param dateStyle
* @return
*/
public static <T> T readValue(String content, TypeReference<T> valueTypeRef, String dateStyle){
try {
ObjectMapper objectMapper = getObjectMapper(dateStyle);
return objectMapper.readValue(content, valueTypeRef);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将json字符串转为对象,日期类型按照给定的样式转换
*
* @param <T> 返回类型
* @param content json字符串
* @param valueType 返回类型
* @param dateStyle 日期格式
* @return 对象
*/
public static <T> T readValue(String content, Class<T> valueType, String dateStyle) {
try {
ObjectMapper objectMapper = getObjectMapper(dateStyle);
return objectMapper.readValue(content, valueType);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据所给的json字符串转换 JsonNode 对象
* @param content
* @return
*/
public static JsonNode readTree(String content){
try {
ObjectMapper objectMapper = getObjectMapper(null);
return objectMapper.readTree(content);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据给定的路径,返回对应的 JsonNode对象
* @param jsonNode
* @param path 路径表达式。 例如:对于{
param:{
transCode:"123"}} 中的transCode可以这样表达,getJsonNode(jsonNode,"param.transCode")
* @return
*/
public static JsonNode getJsonNode(JsonNode jsonNode , String path){
String[] pathArr = path.split("\\.");
JsonNode temp = jsonNode;
for(String filed : pathArr){
temp = temp.get(filed);
}
return temp;
}
/**
* 根据给定的路径,返回对应的 JsonNode对象
* @param json
* @param path
* @return
*/
public static JsonNode getJsonNode(String json , String path){
JsonNode root = readTree(json);
return getJsonNode(root,path);
}
/**
* 得到给定属性的值
* @param jsonNode
* @param path
* @return
*/
public static String getFieldValue(JsonNode jsonNode,String path){
JsonNode node = getJsonNode(jsonNode,path);
if(node==null){
return null;
}
return node.asText();
}
public static String getFieldValue(String json , String path){
JsonNode jsonNode = readTree(json);
return getFieldValue(jsonNode,path);
}
public static void main(String[] args){
// Map map = new HashMap();
// map.put("name", "张三");
// map.put("age", 50);
// map.put("生日", new Date());
// System.out.println(writeValueAsString(map));
// System.out.println(writeValueAsString(map,"yyyy年MM月dd日HH时mm分"));
String str = "{'username':'admin',password:'000000'}";
// String str = "{ \"name\" : \"萧远山\", \"sex\" : \"男\", \"age\" : \"23\",\"address\" : \"河南郑州\"}";
Map<?,?> map = readValue(str,HashMap.class);
System.out.println(map);
}
边栏推荐
- Is there a specific format for English papers?
- What are the recommended thesis translation software?
- 请问大家在什么网站上能查到英文文献?
- 论文的设计方案咋写?
- Feature Engineering: summary of common feature transformation methods
- Digital twin visualization solution digital twin visualization 3D platform
- 洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
- Explain in detail the process of realizing Chinese text classification by CNN
- 来自数砖大佬的 130页 PPT 深入介绍 Apache Spark 3.2 & 3.3 新功能
- Xcode real machine debugging
猜你喜欢

Realization of mask recognition based on OpenCV

JDBC tutorial

Should you study kubernetes?

130 pages of PPT from the brick boss introduces the new features of Apache spark 3.2 & 3.3 in depth

Interpretation of new plug-ins | how to enhance authentication capability with forward auth

Mutual exclusion and synchronization of threads

有哪些比较推荐的论文翻译软件?

What website can you find English literature on?

Seckill system design

Custom throttling function six steps to deal with complex requirements
随机推荐
Question e: merged fruit -noip2004tgt2
有哪些比较推荐的论文翻译软件?
Slf4j + Logback日志框架
yolov5test. Py comment
leetcode 650. 2 keys keyboard with only two keys (medium)
Custom throttling function six steps to deal with complex requirements
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
Top Devops tool chain inventory
PR FAQ, what about PR preview video card?
[shutter] open the third-party shutter project
接口自动化覆盖率统计——Jacoco使用
Is there a specific format for English papers?
Optimization of streaming media technology
MFC gets the current time
Realization of mask recognition based on OpenCV
Mutual exclusion and synchronization of threads
Returns the root node of the largest binary search subtree in a binary tree
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
67 page overall planning and construction plan for a new smart city (download attached)
[shutter] shutter open source project reference