[英]Jersey + Jackson JSON date format serialization - how to change the format or use custom JacksonJsonProvider
[英]how to change date format in json
如何替换json中的数据格式? 例如,我有这样的 json 对象
{
"dt1":"12-12-2020",
"street":"test",
"city":"test2",
"country":"test3",
"dt2":"12-11-2020"
}
结果我想得到
{
"dt1":"12/12/2020",
"street":"test",
"city":"test2",
"country":"test3",
"dt2":"12/11/2020"
}
我有不同的字段名称,所以我们不需要依赖字段名称只需要替换数据格式......我该怎么做???
假设您使用的是 Java 8 或更高版本,并且您拥有的 JSON 对象来自org.json.JSONObject
包,则可以通过以下方式完成:
// Example of jsonStr
/* String jsonStr = "{\n"
+ "\"dt1\":\"12-12-2020\",\n"
+ "\"street\":\"test\",\n"
+ "\"city\":\"test2\",\n"
+ "\"country\":\"test3\",\n"
+ "\"dt2\":\"12-11-2020\"\n"
+ "}";
*/
public String converter(String jsonStr) {
// jsonStr is our original JSON with the date in the dash format (e.g. "12-12-2020")
// Here we convert into our json object
JSONObject json = new JSONObject(jsonStr);
// Get the orginal date value
String dateStr = (String) json.get("dt1");
// Convert the date into new format and update the JSON key 'dt1' with the new value
json.put("dt1", dateConverter(dateStr));
return json.toString();
}
private String dateConverter(String dateStr) {
LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
return date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
}
注 1:Java 8 或更高版本的假设是由于日期转换时的新LocalDate
对象。
注 2:这假设日期采用dd-MM-yyyy
格式而不是MM-dd-yyyy
格式。
注 3:我还会考虑将日期转换移至 Utils 类。
我想到的一种方法是,您可以使用Gson库将一种 json 格式转换为另一种格式。 就像您使用Gson.fromJson将 Json 字符串转换为 Java 对象,然后使用Gson.toJson从 Java 对象转换回所需的 Json 字符串格式一样。 让我分享您尝试的示例代码:
Gson gsonFormat1 = new GsonBuilder().setDateFormat("mm-dd-yyyy").create();
String format1 = "{\n" +
"\"dt1\":\"12-12-2020\",\n" +
"\"street\":\"test\",\n" +
"\"city\":\"test2\",\n" +
"\"country\":\"test3\",\n" +
"\"dt2\":\"12-11-2020\"\n" +
"}";
//Assume Sample is POJO for above json
Sample sampleFormat1 = gsonFormat1.fromJson(format1, Sample.class);
Gson gsonFormat2 = new GsonBuilder().setDateFormat("mm/dd/yyyy").create();
//Your output String here
String s2 = gsonFormat2.toJson(sampleFormat1, Sample.class);
System.out.println("Format2 String => "+s2);
使用上述技术,您不需要知道任何日期字段名称。 基本上所有日期类型字段都可以转换为目标格式。 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.