0

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

DummyBeginner
  • 411
  • 10
  • 34

1 Answers1

1

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.

joelittlejohn
  • 11,665
  • 2
  • 41
  • 54
  • 1
    Thanks. Do you mean **making the class both in the file and inside the code**, By saying `We do this in the integration tests in jsonschema2pojo`? Also is it compulsory to save the class in a file? and Isn't it possible to compile a class without a file (existed in JCodeModel)? – DummyBeginner May 18 '19 at 07:41
  • 1
    You can't compile a jcodemodel. You have to output the Java code from the code model, then compile it. Jcodemodel can output to any writer, it does not have to be a file (but this might be the easiest option). – joelittlejohn May 18 '19 at 11:03
  • Thank you. Do you have any idea about this too: https://stackoverflow.com/q/56196669/190929 – DummyBeginner May 19 '19 at 03:19
  • Regarding compiling classes to be able to use them (.e.g in objectMapper.Read()); couldn't we use this? `Class cls = Class.forName("com.example.ClassName"); Object obj = cls.newInstance();` Does Class.forName() compile the given class? – DummyBeginner May 19 '19 at 05:09
  • 1
    No, it does not. – joelittlejohn May 19 '19 at 08:01