import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class JacksonUtils {
private final static ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
}
/**
* 将对象转换成json字符串,用于将发送的报文打印出到日志
*/
public static String toString(Object object) {
String result = null;
if (null == object)
return result;
try {
result = mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
System.out.println("对象转换成json字符串出错");
}
return result;
}
/**
* 将json字符串转换成对象,用于将发送的报文打印出到日志
* @return
*/
public static <T> T getObjectFromJsonString(String jsonStr, Class<T> responseType) {
T result = null;
if (null == jsonStr)
return result;
try {
result = mapper.readValue(jsonStr, responseType);
} catch (IOException e) {
e.printStackTrace();
System.out.println("json字符: " + jsonStr +" 串转换成对象出错");
}
return result;
}
/**
* 从文件中读取json字符串,转换成对象列表
* @param fileName
* @param JsonObjectType
* @return
*/
public static <T> List<T> readJsonFromFile(String fileName, Class<T> JsonObjectType){
List<T> result = new ArrayList<T>();
try {
//File file = new File("D:\\work\\raiyitest\\a\\a.txt");
File file = new File(fileName);
InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
BufferedReader br = new BufferedReader(new FileReader(file));
//BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null){
T myRule = getObjectFromJsonString(data, JsonObjectType);
result.add(myRule);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 将对象列表转换成json字符串,写入文件
* @param fileName
* @param jsonObjectList
*/
public static <T> void WriteJsonObjectToFile(String fileName, List<T> jsonObjectList){
try {
//File file = new File("D:\\work\\raiyitest\\a\\a.txt");
File file = new File(fileName);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
BufferedWriter bw = new BufferedWriter(osw);
for(T jsonObject : jsonObjectList){
String myJsonStr = toString(jsonObject);
System.out.println(myJsonStr);
bw.write(myJsonStr);
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
json串和java对象互相转换by jackson
ustbxyls2023-08-14 15:01
相关推荐
仰泳之鹅2 小时前
【杂谈】C语言中的链接属性、声明周期以及static关键字卡兰芙的微笑2 小时前
GDB调试指南:从入门到精通weixin_531651812 小时前
Java 正则表达式优选资源分享2 小时前
PowerToys v0.97.0 Windows 窗口优化 + 搜索工具空空kkk2 小时前
Spring Boot项目的搭建2501_940315262 小时前
【无标题】(leetcode933)最近的请求次数Sheep Shaun2 小时前
深入理解红黑树:从概念到完整C++实现详解每天学习一丢丢2 小时前
Spring Boot 调用泛微 E9 Token 认证 + 创建流程完整教程苦逼的老王2 小时前
《java-使用kkview+libreoffice 实现在线预览ppt、xls、doc、pdf..》没有bug.的程序员2 小时前
Spring Boot 启动原理:从 @SpringBootApplication 到自动配置深度解析