【发布时间】:2021-07-06 09:01:34
【问题描述】:
我是 JSON 新手,为了获取用户的交易详情,我正在从 API 的 JSON 响应中对 Web 服务之一进行 API 调用,交易日期如下所示
{
"trasanction_date": {
"year": 2021,
"month": 6,
"day": 16
}
}
我需要将上述日期转换为 yyyy-mm-dd 格式以将其插入 Cassandra。现在我的转换方式是,我正在从上面的字符串创建新的 JSONObject,比如
JSONObject trasaction = new JSONObject("{\"trasanction_date\":{\"year\":2021,\"month\":6,\"day\":16}}");
JSONObject date = trasaction.get("trasaction_date");
String year = date.getString("year");
String month = date.getString("month");
String day = date.getString("day");
//concatenating the final result to frame the date
String transactionDate = year+month+Day
有没有一种方法可以有效地将上述 JSON 格式转换为 yyyy-mm-dd 格式,而无需提取和连接字符串。请提前帮助解决上述问题。
【问题讨论】:
-
您需要多一点才能匹配所需的模式(您缺少连字符并且没有强制执行月份和日期的位数 - 考虑使用 String.format(String,Object...) . 如果您的数据模型不仅仅是从客户端到数据库的传递,请考虑使用 java.time.LocalDate。