简体   繁体   English

将json字符串转换为Java源代码不起作用

[英]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我有一个动态 JSON 模式,我需要在运行时将其转换为 Java 源代码
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...当我打破 json 结构(只是为了测试 jackson 是否正常工作)时,我确实得到了 Jackson 异常...

@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);
}

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.根据这里的答案,您需要覆盖 DefaultGenerationConfig 中的另一个方法才能使其工作。 Adding the following code to your example worked for me:将以下代码添加到您的示例中对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM