java - 如何更改json中的日期格式

标签 java 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 类。

关于java - 如何更改json中的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59950654/

相关文章:

python - 如何获取日志字符串的最后一部分并将其解释为 json?

java - 将 JSON 对象解析为 Restful Web 服务

java - 使用 Launch4j 从 .jar 编译为 .exe 时无法访问资源文件夹

java - C++ 与 Java 原始浮点类型

php - 偏移量 0 对 MySQL 结果索引 10 无效,无法从 mysql php 检索数据

带有重音/拉丁字符的 JSON 请求

javascript - manifest.json 应该引用 auth.js 吗?

java - 如何使用 Context 上下文调用方法

java - 如何在 Map 中控制 JPA 列名

java - 如何使用套接字将移动应用程序从您的 Android 移动设备连接到您的笔记本电脑服务器?