問題背景:在将包含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());
}
}
運作後效果: