0

I am trying to get the data from firebase using RestAPI. So i have integrated with Spring RestTemplate to receive the GET data. My json as below

{
  "alanisawesome": {
    "city": "US",
    "name": "XYZ school"
  },
  "gracehop": {
    "city": "CA",
    "name": "ABC school"
  },
  "nextVal": {
    "city": "Mumbai",
    "name": "GHI School"
  }
}

Since Firebase key(alanisawesome,gracehop,nextVal) created automatically by firebase, I am unable to fetch based on the key.

My Spring Boot code is,

return restTemplate
        .getForObject("https:<FIREBASE>.firebaseio.com/School.json",
            School.class);

My model class is,

public class School {

  private String name;
  private String city;

// Getters and Setters

}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
RenceAbi
  • 522
  • 2
  • 11
  • 26

1 Answers1

0

The REST template getForObject method is meant to be used with singular objects. So you can use it to get a single school, with:

restTemplate
    .getForObject("https:<FIREBASE>.firebaseio.com/School/alanisawesome.json", School.class);

But your School.json has the data for multiple schools under it, with unknown keys. This means you can't use getForObject with the School.class directly.

This tutorial has a section on either using a ParameterizedTypeReference, or a wrapper class, which both sound promising. For you that means you'd either need to use new ParameterizedTypeReference<List<School>>, or would need to create a SchoolList class.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I tried with ParameterizedTypeReference which throws `com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT` and I tried WrapperClass also which gives `null response`. Could you please help – RenceAbi Sep 29 '19 at 14:37
  • It looks like it doesn't recognize the structure as a `List`. This makes sense in hindsight, as an object has meaningful keys, which must be read too. See https://stackoverflow.com/questions/20837856/can-not-deserialize-instance-of-java-util-arraylist-out-of-start-object-token (the first result I get when I search for the error message you shared), and it seems that a `Collection` might be the way to go. – Frank van Puffelen Sep 29 '19 at 15:12