Class JsonOutputParser<T>

java.lang.Object
com.tnsai.parser.JsonOutputParser<T>
Type Parameters:
T - the target type
All Implemented Interfaces:
OutputParser<T>

public class JsonOutputParser<T> extends Object implements OutputParser<T>
JSON-based output parser that converts LLM JSON output into Java objects.

Features:

  • Automatic JSON extraction from markdown code blocks
  • Support for Java Records and POJOs
  • Field validation with annotations
  • Detailed error messages for LLM correction

Usage


 // For a record
 record Person(String name, int age) {}
 JsonOutputParser<Person> parser = JsonOutputParser.forType(Person.class);

 // Parse LLM output (handles JSON in markdown blocks too)
 ParseResult<Person> result = parser.parse("""
     Here's the person data:
     ```json
     {"name": "John", "age": 30}
     ```
     """);

 Person person = result.get();
 
  • Method Details

    • forType

      public static <T> JsonOutputParser<T> forType(Class<T> targetType)
      Creates a parser for the given type with default settings.
      Type Parameters:
      T - the type
      Parameters:
      targetType - the target class
      Returns:
      new parser
    • builder

      public static <T> JsonOutputParser.Builder<T> builder(Class<T> targetType)
      Creates a builder for customizing the parser.
      Type Parameters:
      T - the type
      Parameters:
      targetType - the target class
      Returns:
      new builder
    • parse

      public ParseResult<T> parse(String output)
      Description copied from interface: OutputParser
      Parses the raw LLM output into the target type.
      Specified by:
      parse in interface OutputParser<T>
      Parameters:
      output - the raw string output from the LLM
      Returns:
      parse result containing either the parsed object or error details
    • getTargetType

      public Class<T> getTargetType()
      Description copied from interface: OutputParser
      Returns the target class this parser produces.
      Specified by:
      getTargetType in interface OutputParser<T>
      Returns:
      the target class
    • getFormatInstruction

      public String getFormatInstruction()
      Description copied from interface: OutputParser
      Returns a format instruction string to include in the LLM prompt.

      This helps guide the LLM to produce output in the expected format.

      Specified by:
      getFormatInstruction in interface OutputParser<T>
      Returns:
      format instruction for the prompt
    • getSchemaDescription

      public String getSchemaDescription()
      Description copied from interface: OutputParser
      Returns a schema description of the expected output format.
      Specified by:
      getSchemaDescription in interface OutputParser<T>
      Returns:
      schema description (e.g., JSON Schema, example)