Я новичок в кодировании, и я впервые пишу в StackOverflow, поэтому, пожалуйста, дайте мне знать, если мне нужно добавить что-нибудь еще, чтобы помочь с ответами. Я использую Java с Spring Boot и конвертером сообщений Jackson.
Это ошибка, которую я получаю:
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Recipe': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (String)" Recipe{title=Recipe Puppyversion=0.1, href=http://www.recipepuppy.com/, results=[Results{title=Roasted Vegetable and Prosciutto Lasagna with Alfredo Sauce, href=http://www.epicurious.com/recipes/food/views/Roasted-Vegetable-and-Prosciutto-Lasagna-with-Alfredo-Sauce-104591, ingredients=tomato, prosciutto, alfredo sauce, bell pepper, thumbnail=http://img.recipepuppy.com/122397.jpg}, Results{title=Party-Size Greek Couscous Salad, href=http://allrecipes.com/Recipe/Party-Size-Greek-Couscous-Salad/De"[truncated 3109 chars]; line: 1, column: 8]
com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1840)
com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:722)
com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2868)
com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1914)
com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:773)
com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4340)
com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4189)
com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3205)
com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3173)
com.whatsfordinner.app.controller.RecipeController.getRecipeResults(RecipeController.java:73)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:566)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
Вот пример ответа от Recipe Puppy API:
{
"title":"Recipe Puppy"
"version":0.1
"href":"http://www.recipepuppy.com/"
"results":[
0:{
"title":"Monterey Turkey Omelet"
"href":"http://allrecipes.com/Recipe/Monterey-Turkey-Omelet/Detail.aspx"
"ingredients":"butter, eggs, garlic, green pepper, monterey jack cheese, onions, turkey, water"
"thumbnail":"http://img.recipepuppy.com/5506.jpg"
}
1:{
"title":"Canadian Bacon Omelet"
"href":"http://www.recipezaar.com/Canadian-Bacon-Omelet-309202"
"ingredients":"butter, canadian bacon, cheddar cheese, eggs, garlic, onions, potato, red pepper,
sour cream"
"thumbnail":""
}
]
}
Вот моя модель рецепта:
package com.whatsfordinner.app.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.ArrayList;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Recipe implements Serializable {
private static final long serialVersionUID = -3913629036907715099L;
private String title;
private Number version;
private String href;
private ArrayList<Results> results;
public Recipe() {
}
// getters and setters
@Override
public String toString() {
return "Recipe{" +
"title=" + title +
"version=" + version +
", href=" + href +
", results=" + results +
", true" +
"}";
}
}
Вот моя модель результатов:
package com.whatsfordinner.app.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Results implements Serializable {
private static final long serialVersionUID = -3913629036907715099L;
private String title;
private String href;
private String ingredients;
private String thumbnail;
public Results() {
}
// getters and setters
@Override
public String toString() {
return "Results{" +
"title=" + title +
", href=" + href +
", ingredients=" + ingredients +
", thumbnail=" + thumbnail +
"}";
}
}
Вот мой RecipeController:
package com.whatsfordinner.app.controller;
import ...
@RestController
@RequestMapping("/")
public class RecipeController {
@Autowired
private IngredientDao ingredientDao;
public String ingredientString;
public ClientHttpResponse response;
@GetMapping("home/recipes")
public String getRecipeResults(Model model) throws IOException {
Iterable<Ingredient> ingredients = ingredientDao.findAll();
String searchStr = "";
// iterate through ingredients, create search string to add to backend of api address
for (Ingredient ingredient : ingredients) {
ingredientString = ingredientString + ingredient.getIngredientName() + ",";
String subStr = ingredientString.substring(0, ingredientString.length() - 1);
searchStr = subStr.replaceAll("null", "");
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add((request, body, execution) -> {
ClientHttpResponse response = execution.execute(request,body);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
});
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
//Add the Jackson Message converter
messageConverters.add(new MappingJackson2HttpMessageConverter());
//Add the message converters to the restTemplate
restTemplate.setMessageConverters(messageConverters);
final String url = ("http://www.recipepuppy.com/api/?i=" + searchStr);
ResponseEntity<Recipe> recipes = restTemplate.exchange(url, HttpMethod.GET, (HttpEntity<?>) response, Recipe.class);
// convert to string and remove characters that are giving parse errors
String stringRecipes = recipes.toString();
String recipesFixed = stringRecipes.replaceAll("<", "");
String recipesFixedFinal = recipesFixed.replaceFirst(Pattern.quote("200,"), " ");
ObjectMapper mapper = new ObjectMapper();
Recipe jsonObj = mapper.readValue(recipesFixedFinal, Recipe.class);
if (jsonObj != null) {
model.addAttribute("recipes", jsonObj);
model.addAttribute("title", "Your Recipes");
return "recipes";
}
return "error";
}
}