I want to automatically generate classes form various receiving API json replies. Then, generate objects inside the code using these classes have been made already.
I'm utilizing jsonschema2pojo library. With the example code I tried, The library generates classes as files.
JCodeModel codeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public SourceType getSourceType() {
return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(
new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, apiNodeName, "com.example", apiResultAsString);
codeModel.build(Files.createTempDirectory("tessst").toFile());
I need to save the generated class both as a Class inside the code (something like: ClassType ClassName = codeModel.build();
) and the file (which already is being generated) for further access in the future. How could I do this?
Then, create objects by mapping the JSON output to the generated class via Jackson
and save those objects in a collection.
Thanks
We do this in the integration tests in jsonschema2pojo, so have a look at those tests. You need to compile the class, and to do that you just need to use any compiler API that can be invoked programmatically.
Once you have the class file you can use the object mapper to create instances of it.