J'ai essayé ceci :
class Timings {
private String cookTime;
private String prepTime;
private String totalTime;
public String getCookTime() {
return cookTime;
}
public void setCookTime(String cookTime) {
this.cookTime = cookTime;
}
public String getPrepTime() {
return prepTime;
}
public void setPrepTime(String prepTime) {
this.prepTime = prepTime;
}
public String getTotalTime() {
return totalTime;
}
public void setTotalTime(String totalTime) {
this.totalTime = totalTime;
}
@Override
public String toString() {
return "Timings [cookTime=" + cookTime + ", prepTime=" + prepTime + ", totalTime=" + totalTime + "]";
}
}
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Timings obj = mapper.readValue(new File("C:\\Users\\Anish\\Desktop\\abc.json"), Timings.class);
String totalTime = obj.getTotalTime().split("PT")[1];
int total = 0;
if (totalTime != null && !totalTime.isEmpty()) {
total = returnTotalTime(totalTime);
}
ObjectNode mainNode = mapper.createObjectNode();
ObjectNode timingNode = mapper.createObjectNode();
childNode.put("totalTime", (total > 9) ? (total / 10) : total);
mainNode.set("Timings", timingNode);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mainNode);
System.out.println(json);
}
private static int returnTotalTime(String totalTime) {
if (totalTime != null && !totalTime.isEmpty()) {
String[] timeValues = totalTime.split("H");
if (timeValues.length == 0) {
return 0;
} else if (timeValues.length < 2) {
if (timeValues[0].contains("M")) {
return (timeValues[0].split("M").length <= 0) ? 0
: timeValues[0].split("M")[0].isEmpty() ? 0 : Integer.parseInt(timeValues[0].split("M")[0]);
}
return timeValues[0].isEmpty() ? 0 : Integer.parseInt(timeValues[0]) * 60;
}
int hour = timeValues[0].isEmpty() ? 0 : Integer.parseInt(timeValues[0]) * 60;
int mins = (timeValues[1].split("M").length <= 0) ? 0
: timeValues[1].split("M")[0].isEmpty() ? 0 : Integer.parseInt(timeValues[1].split("M")[0]);
return (hour + mins);
}
return 0;
}
abc.json
{
"cookTime": "PT1H",
"prepTime": "PT10M",
"totalTime": "PT1H10M"
}
Sortie :
{
"Timings" : {
"totalTime" : "7"
}
}
Quand "totalTime": "PT30M"
, alors :
Sortie :
{
"Timings" : {
"totalTime" : "3"
}
}
Quand "totalTime": "PT23M"
, alors :
Sortie :
{
"Timings" : {
"totalTime" : "2"
}
}