I have some nested classes in Java, simplified here. Getters and setters exist.
Example
public class Planet {
@JsonProperty("name")
private String name;
@JsonProperty("moons")
private List<Moon> moons;
}
public class Moon {
@JsonProperty("moonname")
private String name;
@JsonProperty("craters")
private int craters;
}
I want to be able to deserialize the records on mongo (following this same structure) to java objects on the rest controller, specifically the HTTP GET request.
@RestController
@RequestMapping("/planets")
public class PlanetController {
@Autowired
private PlanetService planetService;
@RequestMapping("/")
public List<Planet> getAllPlanets() {
//Need to deserialize here
return planetService.getAll();
}
@RequestMapping("/{name}")
public Planet getItemsWithName(@PathVariable("name") String name) {
//deserialize here
return planetService.getEntryWithName(name.toLowerCase());
}
PlanetService.getAll() is expecting return type of List. getEntryWithName() is expecting return type of Planet.
How can I loop the results in the getAll() so I can deserialize them before they are returned?
Using Jackson's object mapper, I can do the serialization of a Java object to a JSON object.
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File("target/mars.json"), mars);
} catch (IOException e) {
e.printStackTrace();
}
I can probably use readValue for the opposite process but I don't know how to loop the results. I will appreciate the help. Let me know if something is not clear.