从给定的json获取键值的代码是什么,我们可以使用哈希映射吗?如何编写代码?需要更改pojo类?我需要从JSON中获取“ startTime”和“ endTime”
My input Json
{
"active" : 0,
"id" : 3,
"doctorId" :8,
"hospitalId" : 55,
"timeSlot" : [
{ "startTime": "10",
"endTime": "12"
},
{ "startTime": "3",
"endTime": "5"
}
]
}
我的代码
List slot = customDuty.getTimeSlot();
int count = 0;
while (slot.size() > count) {
logger.info("checking"+slot.get(count));
count++;
}
PojoClass
private List timeSlot ;
public List getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(List timeSlot) {
this.timeSlot = timeSlot;
}
输出
checking{startTime=10, endTime=12}
checking{startTime=3, endTime=5}
答案 0 :(得分:1)
如果您正在使用SpringBoot Java,则需要在POM中添加Jackson依赖项
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
然后您需要使用POJO映射json文件
public class ObjectMapperDemo {
public Hospital readJsonWithObjectMapper() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Hospital hos = objectMapper.readValue(new File("hospital.json"), Hospital.class);
return hospital;
}
}
医院实体类别定义如下:
import java.util.List;
public class Hospital {
private boolean active;
private int id;
private int doctorId;
private int hospitalId;
private List<TimeSlot> timeSlot;`
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDoctorId() {
return doctorId;
}
public void setDoctorId(int doctorId) {
this.doctorId = doctorId;
}
public int getHospitalId() {
return hospitalId;
}
public void setHospitalId(int hospitalId) {
this.hospitalId = hospitalId;
}
public List<TimeSlot> getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(List<TimeSlot> timeSlot) {
this.timeSlot = timeSlot;
}
@Override
public String toString() {
return "Hospital{" +
"active=" + active +
", id=" + id +
", doctorId=" + doctorId +
", hospitalId=" + hospitalId +
", timeSlot=" + timeSlot +
'}';
}
}
答案 1 :(得分:0)
最java的风格是创建一个TimeSlot pojo
class TimeSlot {
private int startTime;
private int endTime;
// getters and setters
}
然后进入您的主要实体
class MainEntity {
private List<TimeSlot> timeSlot;
// getters and setters
}
然后让spring(球衣)为您解析。
用法:
mainEntity.getTimeSlots().foreach(timeSlot -> logger.log(
"checking\{startTime={}, endTime={}\}",
timeSlot.getStartTime(),
timeSlot.getEndTime(),
))
但实际上,您可以采用将HashMap<String, Integer>
作为timeSlot
的类型,并通过其键进行访问的方法。
class MainEntity {
private List<HashMap<String, Integer>> timeSlot;
// getters and setters
}
mainEntity.getTimeSlots().foreach(timeSlot -> logger.log(
"checking\{startTime={}, endTime={}\}",
timeSlot.get("startTime"),
timeSlot.getEndTime("endTime"),
))