问题背景:在将包含LocalDateTime字段类型的Java对象转化为Json字符串时,转换异常
package com.java.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.development.centre.core.entity.News;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class test {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
String today = DateTimeFormatter.ofPattern("yyyy-MM-dd [HH:mm:ss]").format(now);
News news = new News(today, 1, true, false, false,
false, false, 1, now, 0, "0", "0", 1);
System.out.println(JSON.toJSONString(news));
System.out.println(JSONObject.toJSONString(news));
}
}
上面是报错代码,下面是报错信息:
解决方法:
将JSON(com.alibaba.fastjson.JSONObject)包改为其他资源包路径,比如JSON(org.json.JSONObject)即可
替换后效果:
package com.java.test;
import org.json.JSONObject;
import com.development.centre.core.entity.News;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class test {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
String today = DateTimeFormatter.ofPattern("yyyy-MM-dd [HH:mm:ss]").format(now);
News news = new News(today, 1, true, false, false,
false, false, 1, now, 0, "0", "0", 1);
System.out.println(new JSONObject(news).toString());
}
}
运行后效果:
本文介绍了一种在Java中将包含LocalDateTime字段的对象转换为Json字符串时遇到的问题及解决方案。通过更换使用的JSON库,从com.alibaba.fastjson.JSONObject改为org.json.JSONObject,成功避免了转换异常,实现了正确转化。
3252

被折叠的 条评论
为什么被折叠?



