I have written this below code to read JSON and save in PostgreSQL, but it does not work when it is nested, only the last two records are added. How can I loop nested arrray HD. There 2 nested arrays HD in this case. How can I make this work? should I have to loop HD array or am I doing something wrong here?
{
"result": {
"HD": [
{
"ADDR": "2218",
"CAT": "s",
"NAME": "Last"
}
],
"HD": [
{
"ADDR": "2219",
"CAT": "w",
"NAME": "Last"
},
"HD":
{
"ADDR": "2220",
"CAT": "m",
"NAME": "Last"
}
]
}
My domain classes
@AllArgsConstructor
@Data
@Entity
@Table(name ="receive", schema = "public")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response {
@Id
@JsonProperty("ADDR")
@Column(name = "addr")
private String ADDR;
@JsonProperty("CAT")
@Column(name = "cat")
private String CAT;
@JsonProperty("NAME")
@Column(name = "name")
private String NAME;
}
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
@JsonProperty("HD")
List<Response> HD = new ArrayList<>();
}
@Getter
public class AddressArray {
Result result;
}
This is my main class; I'm pretty sure I'm missing something here
public class ReceiveApplication {
public static void main(String[] args) {
SpringApplication.run(ReceiveApplication.class, args);
}
@Bean
CommandLineRunner runner(ResponseService responseService) {
return args -> {
ObjectMapper mapper = new ObjectMapper();
TypeReference<AddressArray> typeReference1 = new TypeReference<AddressArray>() {
};
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/response.json");
try {
AddressArray addressArray = mapper.readValue(inputStream, typeReference1);
List<Response> responses = addressArray.getResult().getHD();
responseService.save(responses);
System.out.println(responses);
System.out.println("Data saved in table");
} catch (IOException e) {
System.out.println("not saved " + e.getMessage());
}
};
}
}