java - Spring Boot com.fasterxml.jackson.core.JsonParseException : Unrecognized token 'Recipe'

标签 java spring spring-boot spring-mvc jackson

我是编码新手,这是我第一次在 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";
    }

}

最佳答案

您的 toString() 未创建有效的 JSON。 JSON 的格式如下所示:

{
  "Recipe" : "Alfredo Sauce"
}

但是你的看起来像这样:

{
  recipe=Alfredo sauce
}

了解有关 JSON 的更多信息:https://www.w3schools.com/js/js_json_intro.asp

关于java - Spring Boot com.fasterxml.jackson.core.JsonParseException : Unrecognized token 'Recipe' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59937587/

相关文章:

在 Linux 上找不到 Javax.Mail Authenticator

java - Spring Boot NoSuchMethodError

java - 在 Spring RedisTemplate 中使用 TTL 的 Redis MSET

java - 尝试模拟 Elastic Search 的 RestHighLevelClient 时出现 NullPointerException 问题

java - Spring中每个方法执行前如何调用自定义验证

java - 输入大小的问题,java noob

java - 如何从 .bat 脚本在单独的窗口中启动 JAR?

java - 在java中使用NPC AI的用户脚本

java - 加载时编织 (AspectJ) : Hystrix breaks transaction propagation

spring - JavaFx 12 Spring,Maven 未找到前缀插件