当前位置:网站首页>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);
}
边栏推荐
- 程序分析与优化 - 9 附录 XLA的缓冲区指派
- Talk with the interviewer about the pit of MySQL sorting (including: duplicate data problem in order by limit page)
- Bypass AV with golang
- Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
- NC20806 区区区间间间
- NC50965 Largest Rectangle in a Histogram
- 英文论文有具体的格式吗?
- 多进程编程(五):信号量
- Markdown使用教程
- Codeforces Round #771 (Div. 2)---A-D
猜你喜欢
QT 如何将数据导出成PDF文件(QPdfWriter 使用指南)
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
[shutter] Introduction to the official example of shutter Gallery (project introduction | engineering construction)
67 page overall planning and construction plan for a new smart city (download attached)
开源了 | 文心大模型ERNIE-Tiny轻量化技术,又准又快,效果全开
Digital collection trading website domestic digital collection trading platform
Custom throttling function six steps to deal with complex requirements
论文的英文文献在哪找(除了知网)?
Feature Engineering: summary of common feature transformation methods
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
随机推荐
Missing number
maya渔屋建模
What is the standard format of a 2000-3000 word essay for college students' classroom homework?
Realization of mask recognition based on OpenCV
Monitor container runtime tool Falco
[reading notes] phased summary of writing reading notes
JSON转换工具类
35 pages dangerous chemicals safety management platform solution 2022 Edition
布隆过滤器
免费自媒体必备工具分享
RTP 接发ps流工具改进(二)
zhvoice
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
Interface difference test - diffy tool
Talk with the interviewer about the pit of MySQL sorting (including: duplicate data problem in order by limit page)
NC50965 Largest Rectangle in a Histogram
多进程编程(四):共享内存
MySQL advanced learning notes (III)
Which websites can I search for references when writing a thesis?
NC17059 队列Q