当前位置:网站首页>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);
}
边栏推荐
- yolov5train. py
- Blue decides red - burst CS teamserver password
- MFC gets the current time
- Using tensorflow to realize voiceprint recognition
- 英文论文有具体的格式吗?
- TypeError: Cannot read properties of undefined (reading ***)
- Understanding and application of least square method
- What is the standard format of a 2000-3000 word essay for college students' classroom homework?
- NC24325 [USACO 2012 Mar S]Flowerpot
- NC24840 [USACO 2009 Mar S]Look Up
猜你喜欢

Maya fishing house modeling

Where can I find the English literature of the thesis (except HowNet)?

Multiprocess programming (II): Pipeline

Should you study kubernetes?

RTP 接发ps流工具改进(二)

MySQL 23道经典面试吊打面试官

Understanding and application of least square method

What are the projects of metauniverse and what are the companies of metauniverse

redis21道经典面试题,极限拉扯面试官

Explain in detail the process of realizing Chinese text classification by CNN
随机推荐
form表单实例化
UART、RS232、RS485、I2C和SPI的介绍
Open Source | Wenxin Big Model Ernie Tiny Lightweight Technology, Accurate and Fast, full Open Effect
yolov5detect. Py comment
Go自定义排序
秒杀系统设计
关于Unity屏幕相关Screen的练习题目,Unity内部环绕某点做运动
Question e: merged fruit -noip2004tgt2
TypeError: Cannot read properties of undefined (reading ***)
Is the multitasking loss in pytoch added up or backward separately?
直击产业落地!飞桨重磅推出业界首个模型选型工具
Interpretation of new plug-ins | how to enhance authentication capability with forward auth
NC24325 [USACO 2012 Mar S]Flowerpot
How to write the design scheme of the thesis?
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
接口差异测试——Diffy工具
TypeError: Cannot read properties of undefined (reading ***)
Judge whether the binary tree is full binary tree
Thinkadmin V6 arbitrary file read vulnerability (cve-2020-25540)
Which software can translate an English paper in its entirety?