JSON to POJO returning Null

Asked

Viewed 145 times

0

I’m making a request for the site’s API swapi and whenever I do the conversion from JSON to POJO, I get the NULL return

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "https://swapi.co/api/planets/?format=json";
PlanetaEntity response = restTemplate.getForObject(fooResourceUrl, PlanetaEntity.class);

But when there is no conversion, already send direct to String, the return is not null.

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "https://swapi.co/api/planets/?format=json";
String response = restTemplate.getForObject(fooResourceUrl, String.class);

I believe there’s some problem in my Planetaentity class, but I haven’t been able to identify.

@JsonIgnoreProperties(ignoreUnknown = true)

@Document(collection = "starwars")
public class PlanetaEntity implements Serializable {

private static final long serialVersionUID = -8511702512631671990L;

@Id
private ObjectId _id;

private String name;

private String climate;

private String terrain;

private List<String> films
// Getters e Setters

Remembering that I am using Mongodb for database.

  • 1

    The URL does not return data from a single planet, but an object on which one of the camps (results) is a list of planets. So there’s no way to map this to a single PlanetaEntity.

1 answer

1


As quoted in the comments, your return JSON has the following structure:

{
"count":61,
"next":"https://swapi.co/api/planets/?format=json&page=2",
"previous":null,
"results":[{..}]
}

Note that the Planetaentity class is what is inside Results. To serialize correctly you need to use the correct matching class. For example:

Planetaentitypagination

public class PlanetaEntityPagination {
    private Integer count;
    private String next;
    private String previous;
    private List<PlanetaEntity> results;

    //getters e setters
}

And your code mapping for Jackson to deserialize in this class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.