当前位置:网站首页>JSON conversion tool class
JSON conversion tool class
2022-07-03 00:23: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 Tool class <br>
* Create by: name:luyong <br>email: 15701203325@163.com
*/
public class JsonUtils {
/**
* Default date format
*/
private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static ObjectMapper defaultObjectMapper = getObjectMapper(null);
/**
* Return to one Object object
* @param datePattern, Specify the date string format that can be processed , If not specified, the default is 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));
// Allow field names not to use quotation marks
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
// Single quotation marks are allowed
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// Ignore unrecognized parameters ( solve json Multi attribute in string , And undefined in the class )
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Converts an object to string when ,json Of key Whether according to the object field The natural order of
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, false);
return objectMapper;
}
/**
* Convert the specified object to json character string . Date type according to yyyy-MM-dd HH:mm:ss Convert the format of to string
* @param obj object
* @return json character string
*/
public static String writeValueAsString(Object obj){
try {
return getObjectMapper(null).writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Convert the specified object to json character string
* @param object
* @param datePattern Specify the converted date format
* @return
*/
public static String writeValueAsString(Object object, String datePattern) {
try {
return getObjectMapper(datePattern).writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Convert the specified object to json character string
* @param object
* @param datePattern Specify the converted date format
* @param indentOutput Indent output
* @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);
}
}
/**
* take json String to object
* @param <T> Return type
* @param content json character string
* @param valueType Return type
* @return object
*/
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);
}
}
/**
* take json Convert to object
* @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);
}
}
/**
* take json Convert to object
* @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);
}
}
/**
* take json String to object , The date type is converted according to the given style
*
* @param <T> Return type
* @param content json character string
* @param valueType Return type
* @param dateStyle Date format
* @return object
*/
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);
}
}
/**
* According to what is given json String conversion JsonNode object
* @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);
}
}
/**
* According to the given path , Return the corresponding JsonNode object
* @param jsonNode
* @param path Path expression . for example : about {
param:{
transCode:"123"}} Medium transCode It can be expressed as ,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;
}
/**
* According to the given path , Return the corresponding JsonNode object
* @param json
* @param path
* @return
*/
public static JsonNode getJsonNode(String json , String path){
JsonNode root = readTree(json);
return getJsonNode(root,path);
}
/**
* Get the value of the given attribute
* @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", " Zhang San ");
// map.put("age", 50);
// map.put(" Birthday ", new Date());
// System.out.println(writeValueAsString(map));
// System.out.println(writeValueAsString(map,"yyyy year MM month dd Japan HH when mm branch "));
String str = "{'username':'admin',password:'000000'}";
// String str = "{ \"name\" : \" Xiao Yuanshan \", \"sex\" : \" male \", \"age\" : \"23\",\"address\" : \" Zhengzhou, Henan \"}";
Map<?,?> map = readValue(str,HashMap.class);
System.out.println(map);
}
边栏推荐
- v8
- zhvoice
- Digital collection trading website domestic digital collection trading platform
- Returns the maximum distance between two nodes of a binary tree
- Leetcode skimming - game 280
- How QT exports data to PDF files (qpdfwriter User Guide)
- DotNet圈里一个优秀的ORM——FreeSql
- AcWing_ 188. Warrior cattle_ bfs
- Define MySQL function to realize multi module call
- Is the multitasking loss in pytoch added up or backward separately?
猜你喜欢
多进程编程(二):管道
Feature Engineering: summary of common feature transformation methods
Bloom filter
setInterval定时器在ie不生效原因之一:回调的是箭头函数
Chinatelecom has maintained a strong momentum in the mobile phone user market, but China Mobile has opened a new track
130 pages of PPT from the brick boss introduces the new features of Apache spark 3.2 & 3.3 in depth
洛谷_P2010 [NOIP2016 普及组] 回文日期_折半枚举
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
Is the multitasking loss in pytoch added up or backward separately?
Digital twin smart factory develops digital twin factory solutions
随机推荐
Mutual exclusion and synchronization of threads
Chapter 4 of getting started with MySQL: data types stored in data tables
NC50965 Largest Rectangle in a Histogram
JSON转换工具类
Sysdig analysis container system call
form表单实例化
Improvement of RTP receiving and sending PS stream tool (II)
MATLAB signal processing [Q & a notes-1]
在线预览Word文档
Blue decides red - burst CS teamserver password
How to specify const array in the global scope of rust- How to specify const array in global scope in Rust?
pageoffice-之bug修改之旅
详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
zhvoice
NC24325 [USACO 2012 Mar S]Flowerpot
Missing number
35 pages dangerous chemicals safety management platform solution 2022 Edition
How QT exports data to PDF files (qpdfwriter User Guide)
Implement the foreach method of array
请问大家在什么网站上能查到英文文献?