Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

前端 未结 5 1065
攒了一身酷
攒了一身酷 2020-12-13 18:05

I have rest url that gives me all countries - http://api.geonames.org/countryInfoJSON?username=volodiaL.

I use RestTemplate from spring 3 to parse returned json into

相关标签:
5条回答
  • 2020-12-13 18:11

    Another solution:

    public class CountryInfoResponse {
      private List<Object> geonames;
    }
    

    Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

    0 讨论(0)
  • 2020-12-13 18:18

    For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer

    Spring Data Rest - _links

    0 讨论(0)
  • 2020-12-13 18:24

    You need to do the following:

    public class CountryInfoResponse {
    
       @JsonProperty("geonames")
       private List<Country> countries; 
    
       //getter - setter
    }
    
    RestTemplate restTemplate = new RestTemplate();
    List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();
    

    It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

    0 讨论(0)
  • 2020-12-13 18:26

    If you want to avoid using an extra Class and List<Object> genomes you could simply use a Map.

    The data structure translates into Map<String, List<Country>>

    String resourceEndpoint = "http://api.geonames.org/countryInfoJSON?username=volodiaL";
    
    Map<String, List<Country>> geonames = restTemplate.getForObject(resourceEndpoint, Map.class);
    
    List<Country> countries = geonames.get("geonames");
    
    0 讨论(0)
  • 2020-12-13 18:28

    In my case, I was getting value of <input type="text"> with JQuery and I did it like this:

    var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
     "firstName": inputFirstName[0] , "email": inputEmail[0].value}
    

    And I was constantly getting this exception

    com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream@39cb6c98; line: 1, column: 54] (through reference chain: com.springboot.domain.User["firstName"]).

    And I banged my head for like an hour until I realised that I forgot to write .value after this"firstName": inputFirstName[0].

    So, the correct solution was:

    var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
     "firstName": inputFirstName[0].value , "email": inputEmail[0].value}
    

    I came here because I had this problem and I hope I save someone else hours of misery.

    Cheers :)

    0 讨论(0)
提交回复
热议问题