如何替换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/