Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Thursday, October 20, 2016

Cannot Parse a JSON response that is received by RestTemplate

Cannot Parse a JSON response that is received by RestTemplate


I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.

The request sent by the client was syntactically incorrect.

Code

RestTemplate restTemplate = new RestTemplate();  restTemplate.getMessageConverters().add(new                                           MappingJackson2HttpMessageConverter());          ResponseEntity responseEntity = restTemplate                  .getForEntity(                          "http://primesport.sieenasoftware.com/QryApi                           /GetEvents?                           username=username&                           password=password&                           userid=23",                           Results.class);          System.err.println(">>" + responseEntity.getBody().getEvents().size());  

Classes

Results

public class Results {      private List events;      getter and setter  }  

Events

   public class Event {         private long eventId;         private String name;         private String subTitle;         private String description;         private String localDate;         private String localDateFrom;         private String imageUrl;         private int venueId;         private String venue;         private int availableTickets;         private long performerId;         private String performer;         private String performerType;         private int subcategoryId;         private String urlCategoryName;         private String metaTitle;         private String metaDescription;         private String primeSportUrl;         private String sectionWiseView;         private String venueCity;         private String venueState;         private String snippetDate;         private int eiProductionId;         private boolean requireBillingAsShipping;      public long getEventId() {          return eventId;      }      public void setEventId(long eventId) {          this.eventId = eventId;      }      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }      public String getSubTitle() {          return subTitle;      }      public void setSubTitle(String subTitle) {          this.subTitle = subTitle;      }      public String getDescription() {          return description;      }      public void setDescription(String description) {          this.description = description;      }      public String getLocalDate() {          return localDate;      }      public void setLocalDate(String localDate) {          this.localDate = localDate;      }      public String getLocalDateFrom() {          return localDateFrom;      }      public void setLocalDateFrom(String localDateFrom) {          this.localDateFrom = localDateFrom;      }      public String getImageUrl() {          return imageUrl;      }      public void setImageUrl(String imageUrl) {          this.imageUrl = imageUrl;      }      public int getVenueId() {          return venueId;      }      public void setVenueId(int venueId) {          this.venueId = venueId;      }      public String getVenue() {          return venue;      }      public void setVenue(String venue) {          this.venue = venue;      }      public int getAvailableTickets() {          return availableTickets;      }      public void setAvailableTickets(int availableTickets) {          this.availableTickets = availableTickets;      }      public long getPerformerId() {          return performerId;      }      public void setPerformerId(long performerId) {          this.performerId = performerId;      }      public String getPerformer() {          return performer;      }      public void setPerformer(String performer) {          this.performer = performer;      }      public String getPerformerType() {          return performerType;      }      public void setPerformerType(String performerType) {          this.performerType = performerType;      }      public int getSubcategoryId() {          return subcategoryId;      }      public void setSubcategoryId(int subcategoryId) {          this.subcategoryId = subcategoryId;      }      public String getUrlCategoryName() {          return urlCategoryName;      }      public void setUrlCategoryName(String urlCategoryName) {          this.urlCategoryName = urlCategoryName;      }      public String getMetaTitle() {          return metaTitle;      }      public void setMetaTitle(String metaTitle) {          this.metaTitle = metaTitle;      }      public String getMetaDescription() {          return metaDescription;      }      public void setMetaDescription(String metaDescription) {          this.metaDescription = metaDescription;      }      public String getPrimeSportUrl() {          return primeSportUrl;      }      public void setPrimeSportUrl(String primeSportUrl) {          this.primeSportUrl = primeSportUrl;      }      public String getSectionWiseView() {          return sectionWiseView;      }      public void setSectionWiseView(String sectionWiseView) {          this.sectionWiseView = sectionWiseView;      }      public String getVenueCity() {          return venueCity;      }      public void setVenueCity(String venueCity) {          this.venueCity = venueCity;      }      public String getVenueState() {          return venueState;      }      public void setVenueState(String venueState) {          this.venueState = venueState;      }      public String getSnippetDate() {          return snippetDate;      }      public void setSnippetDate(String snippetDate) {          this.snippetDate = snippetDate;      }      public int getEiProductionId() {          return eiProductionId;      }      public void setEiProductionId(int eiProductionId) {          this.eiProductionId = eiProductionId;      }      public boolean isRequireBillingAsShipping() {          return requireBillingAsShipping;      }      public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {          this.requireBillingAsShipping = requireBillingAsShipping;      }    }  

Partial Response

[{  "EventId":1000250537,  "Name":"US Open Golf",  "SubTitle":null,  "Description":"US Open Golf Tickets",  "Date":"\/Date(1434873560000)\/",  "LocalDate":"6/20/2015 11:59 PM",  "LocalDateFrom":null,  "ImageUrl":null,  "VenueId":146566,  "Venue":"Chambers Bay Golf Course",  "AvailableTickets":33,  "PerformerId":151551,  "Performer":"US Open Golf",  "PerformerType":"Golf",  "SubcategoryId":55,  "UrlCategoryName":"Sports",  "MetaTitle":null,  "MetaDescription":null,  "PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",  "SectionWiseView":null,  "VenueCity":"UNIVERSITY PLACE",  "VenueState":"WA",  "SnippetDate":null,  "EIProductionId":99985,  "RequireBillingAsShipping":false},  {  "EventId":1000253479,  "Name":"Womens College World Series",  "SubTitle":null,  "Description": .....  

UPDATE

I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.

UPDATE

The code is returning following exception:

    org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token   at [Source: java.io.PushbackInputStream@dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token   at [Source: java.io.PushbackInputStream@dedcd10; line: 1, column: 1]      at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)      at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)      at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)      at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)      at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)      at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)      at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)      at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)      at
com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217) at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45) at com.myproject.web.TicketController.findTicket(TicketController.java:29) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606)

UPDATE

following code returns

Code

try {              System.err.println(">>> primeSport");              RestTemplate restTemplate = new RestTemplate();              restTemplate.getMessageConverters().add(                      new MappingJackson2HttpMessageConverter());              ResponseEntity responseEntity = restTemplate                      .getForEntity(                              "http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",                              Event[].class);              System.err.println(">>" + responseEntity.getBody().length);              System.err.println(">>" + responseEntity.getBody()[0].getEventId());              System.err.println(">>" + responseEntity.getBody()[1].getEventId());          } catch (Exception e) {              e.printStackTrace();          }  

Output

>1532  >0  >0  

Answer by user3587856 for Cannot Parse a JSON response that is received by RestTemplate


You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.

ObjectMapper mapper = new ObjectMapper();        try        {           mapper.writeValue(new File("c://temp/employee.json"), Results);        }  

Answer by burhancerit for Cannot Parse a JSON response that is received by RestTemplate


is this the whole response you get from web service ? if that so, the json text is not valid check it here

copy paste and it will show you the error in it.

My assumption to correct one is like

[{  "EventId":1000250537,  "Name":"US Open Golf",  "SubTitle":null,  "Description":"US Open Golf Tickets",  "Date":"\/Date(1434873560000)\/",  "LocalDate":"6/20/2015 11:59 PM",  "LocalDateFrom":null,  "ImageUrl":null,  "VenueId":146566,  "Venue":"Chambers Bay Golf Course",  "AvailableTickets":33,  "PerformerId":151551,  "Performer":"US Open Golf",  "PerformerType":"Golf",  "SubcategoryId":55,  "UrlCategoryName":"Sports",  "MetaTitle":null,  "MetaDescription":null,  "PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",  "SectionWiseView":null,  "VenueCity":"UNIVERSITY PLACE",  "VenueState":"WA",  "SnippetDate":null,  "EIProductionId":99985,  "RequireBillingAsShipping":false  }]  

But the inner curly-brackets are defining an object without a name, first it should have name so that it can be easier to parse E.g:

"GlossEntry" element has list of variables like yours.

{      "glossary": {          "title": "example glossary",          "GlossDiv": {              "title": "S",              "GlossList": {                  "GlossEntry": {                      "ID": "SGML",                      "SortAs": "SGML",                      "GlossTerm": "Standard Generalized Markup Language",                      "Acronym": "SGML",                      "Abbrev": "ISO 8879:1986",                      "GlossDef": {                          "para": "A meta-markup language, used to create markup languages such as DocBook.",                          "GlossSeeAlso": ["GML", "XML"]                      },                      "GlossSee": "markup"                  }              }          }      }  }  

look at here first.examples The curly brackets with names.

Yours may be look like this

["YourDataObject":{  "EventId":1000250537,  "Name":"US Open Golf",  "SubTitle":null,  "Description":"US Open Golf Tickets",  "Date":"\/Date(1434873560000)\/",  "LocalDate":"6/20/2015 11:59 PM",  "LocalDateFrom":null,  "ImageUrl":null,  "VenueId":146566,  "Venue":"Chambers Bay Golf Course",  "AvailableTickets":33,  "PerformerId":151551,  "Performer":"US Open Golf",  "PerformerType":"Golf",  "SubcategoryId":55,  "UrlCategoryName":"Sports",  "MetaTitle":null,  "MetaDescription":null,  "PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",  "SectionWiseView":null,  "VenueCity":"UNIVERSITY PLACE",  "VenueState":"WA",  "SnippetDate":null,  "EIProductionId":99985,  "RequireBillingAsShipping":false  }]  

[] are for list. Now you have a list without and name again and element in it. And here is another exmple int json list

it shows int list but your list here has object list with a lot of variables.

just a reminder always validate your json data with this validator. saves you time. how to pars is up to your wish. regards

Answer by KDM for Cannot Parse a JSON response that is received by RestTemplate


Can you try the following and see whether helps:

ResponseEntity responseEntity = restTemplate              .getForEntity(                      "http://primesport.sieenasoftware.com/QryApi                       /GetEvents?                       username=username&                       password=password&                       userid=23",                       Events[].class);  System.err.println(">>" + responseEntity.getBody().length);  

For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.

@JsonProperty("EventId")  private long eventId;  @JsonProperty("Name")  private String name;  

Answer by Hossein for Cannot Parse a JSON response that is received by RestTemplate


According to the json format, all you need is using the Event class instead of the Result class. Or change the JSON result to this :

["events": {  "EventId":1000250537,  "Name":"US Open Golf",  "SubTitle":null,  "Description":"US Open Golf Tickets",  "Date":"\/Date(1434873560000)\/",  "LocalDate":"6/20/2015 11:59 PM",  "LocalDateFrom":null,  "ImageUrl":null,  "VenueId":146566,  "Venue":"Chambers Bay Golf Course",  "AvailableTickets":33,  "PerformerId":151551,  "Performer":"US Open Golf",  "PerformerType":"Golf",  "SubcategoryId":55,  "UrlCategoryName":"Sports",  "MetaTitle":null,  "MetaDescription":null,  "PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",  "SectionWiseView":null,  "VenueCity":"UNIVERSITY PLACE",  "VenueState":"WA",  "SnippetDate":null,  "EIProductionId":99985,  "RequireBillingAsShipping":false},  {  "EventId":1000253479,  "Name":"Womens College World Series",  "SubTitle":null,  "Description": .....  

Answer by eXc for Cannot Parse a JSON response that is received by RestTemplate


Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?

Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).

Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.

String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";  MultiValueMap params = new LinkedMultiValueMap();  params.add("username", "username");  params.add("password", "password");  params.add("userid", "23");    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();  System.out.println(uriComponents.toUri());  

Please let me know, how it works out.

Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Related Posts:

0 comments:

Post a Comment

Popular Posts

Fun Page

Powered by Blogger.