public static Quote parseQuoteFromJson()

in sessions/fall24/spring-ai-quotes-llm-in-gke/src/main/java/com/example/quotes/domain/Quote.java [114:136]


  public static Quote parseQuoteFromJson(String input) {
    MapOutputConverter converter = new MapOutputConverter();
    String jsonRegex = "```json(.*?)```json";
    java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(jsonRegex, java.util.regex.Pattern.DOTALL).matcher(input);
    Quote quote = new Quote();
    quote.setQuote(input);
    quote.setId(0l);
    String jsonString = "";
    if (matcher.find()) {
      jsonString = matcher.group(1).trim();
    }  else {
      int startIndex = input.indexOf('{') >=0 ? input.indexOf('{') : 0;
      int endIndex = input.lastIndexOf('}');
      jsonString = input.substring(startIndex, endIndex + 1);
    }
    if(!jsonString.isBlank()) {
      Map<String, Object> result = converter.convert(jsonString.replaceAll("\\\\n", " "));
      quote.setAuthor(result.get("author")!=null ? result.get("author").toString():"");
      quote.setQuote(result.get("quote")!=null ? result.get("quote").toString():"");
      quote.setBook(result.get("book")!=null ? result.get("book").toString():"");
    }
    return quote;
  }