Search code examples
javajackson2

convert json string to Java source code not working


I have a dynamic JSON schema that I need to convert to Java source code at run-time
I found this Jackson example that seems very common
The code is running fine, no exceptions but not generating anything.
When I break the json structure (just to test that jackson is working) I do get Jackson exception...

@Test
public void jsonToJava() throws IOException {   
    JCodeModel codeModel = new JCodeModel();
    String schemaContents ="{\"test\":\"test\"}";

    GenerationConfig config = new DefaultGenerationConfig() {
        @Override
        public boolean isGenerateBuilders() { 
            return true;
        }
    };

    SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
    mapper.generate(codeModel, "HelloWorldClass", "com.my.package", schemaContents);
    File directory = new File("C:\\temp\\gen");
    directory.mkdirs();
    codeModel.build(directory);
}

Solution

  • I don't know anything about that library, but it appears the example doesn't work as is. According to the answers here, you need to override another method in your DefaultGenerationConfig to get this to work. Adding the following code to your example worked for me:

    @Override
    public SourceType getSourceType() {
        return SourceType.JSON;
    }