0

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.

Hermione Granger
  • 217
  • 1
  • 3
  • 9
  • Possible duplicate of [Deserialize JSON to ArrayList using Jackson](https://stackoverflow.com/questions/9829403/deserialize-json-to-arraylistpojo-using-jackson) – vavasthi Feb 12 '19 at 06:01

1 Answers1

0
  public List<Planet> getAllPlanets() {
      List<Planet> planets = planetService.getAll();
      String jsonString = new ObjectMapper().writeValueAsString(planets);
      return planets;
  }
Ankit Gupta
  • 275
  • 3
  • 12