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
相关推荐
lht63193561219 小时前
从Windows通过XRDP远程访问和控制银河麒麟 v10服务器WZTTMoon19 小时前
Spring 配置解析与 @Value 注入核心流程详解阿豪学编程19 小时前
环境变量与程序地址空间程序定小飞19 小时前
基于springboot的健身房管理系统开发与设计wxin_VXbishe19 小时前
springboot在线课堂教学辅助系统-计算机毕业设计源码07741墨倾许20 小时前
《Windows 11 + Docker:极简DVWA靶场搭建全记录》—— 附详细排错指南与最终解决方案信仰_27399324320 小时前
RedisCluster客户端路由智能缓存兰雪簪轩20 小时前
仓颉语言内存布局优化技巧:从字节对齐到缓存友好的深度实践CaracalTiger20 小时前
本地部署 Stable Diffusion3.5!cpolar让远程访问很简单!okjohn20 小时前
《架构师修炼之路》——②对架构的基本认识