当前位置:网站首页>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);
}
边栏推荐
猜你喜欢
![[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)](/img/c5/2f65d37682607aab98443d7f1ba775.jpg)
[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)

Angled detection frame | calibrated depth feature for target detection (with implementation source code)

Improvement of RTP receiving and sending PS stream tool (II)

Realization of mask recognition based on OpenCV

Digital collection trading website domestic digital collection trading platform

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

教育学大佬是怎么找外文参考文献的?
![[target detection] r-cnn, fast r-cnn, fast r-cnn learning](/img/f0/df285f01ffadff62eb3dcb92f2e04f.jpg)
[target detection] r-cnn, fast r-cnn, fast r-cnn learning

Mutual exclusion and synchronization of threads

Open source | Wenxin big model Ernie tiny lightweight technology, which is accurate and fast, and the effect is fully open
随机推荐
CMake基本使用
[shutter] Introduction to the official example of shutter Gallery (learning example | email application | retail application | wealth management application | travel application | news application | a
Xcode real machine debugging
Chapter 3 of getting started with MySQL: database creation and operation
zhvoice
Cmake basic use
Bloom filter
[reading notes] phased summary of writing reading notes
Sysdig analysis container system call
Where can I find the English literature of the thesis (except HowNet)?
Open source | Wenxin big model Ernie tiny lightweight technology, which is accurate and fast, and the effect is fully open
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
哪些软件可以整篇翻译英文论文?
Shell脚本基本使用
67 page overall planning and construction plan for a new smart city (download attached)
MATLAB signal processing [Q & a notes-1]
请问大家在什么网站上能查到英文文献?
Markdown使用教程
Slf4j + logback logging framework
经济学外文文献在哪查?