1

I am trying to write a tool, which will take the json schema from the user where they can specify the attributes they want to extract out the json and save it.

I figured out that using jsonschema and jsonschema2pojo, I can generate the pojo out of schema and json but I dont want to create the File in all 100 instances, instead I want to create in-memory class and want to convert my json to that class.

         String schemaJson = IOUtils.toString(TrySchema.class.getClassLoader()
                .getResourceAsStream("olympic-schema.json"));
        JCodeModel codeModel = new JCodeModel();
        GenerationConfig config = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() { // set config option by overriding method
                return true;
            }
        };

        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
        mapper.generate(codeModel, "ClassName", "com.example",  schemaJson);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CodeWriter codeWriter = new SingleStreamCodeWriter(baos);
        codeModel.build(codeWriter);

        String code = baos.toString(); // you can use toString(charset) if there are special characters in your code
        System.out.println(code);

        ParseContext parseContext = JsonPath.using(Configuration.builder()
                .jsonProvider(new GsonJsonProvider())
                .mappingProvider(new GsonMappingProvider())
                .build());
        JsonArray responseData = parseContext.parse(validResponseData).read("$.[*].[*]", RESPONSE_TYPE);

I am stuck after this, how do I convert it in to List here

 List<ClassName> classNames = GSON.fromJson(responseData, new TypeRef<List<ClassName>>(){}.getType());

Is there any other way to achieve this ? I dont even care to have a intermediate java pojo, If I directly fetch the structure specified in json schema from json, I am good.

plzdontkillme
  • 1,497
  • 3
  • 20
  • 38
  • can you post exception/error ? – Ravi Feb 04 '18 at 05:50
  • JSON schema is used to describe data structures, you cannot use it to extract data. – Henry Feb 04 '18 at 05:59
  • @Henry: why not, I got schema and got converted in to POJO and all I have to reference it in GSON. Having said that, I am open to other ideas of achieving it. – plzdontkillme Feb 04 '18 at 06:23
  • @Ravi, there is not error, I just want to all user a specify the fields / structure they want from the API Json response. – plzdontkillme Feb 04 '18 at 06:23
  • @plzdontkillme You can have more control over the json->java process using [minimal-json](https://github.com/ralfstx/minimal-json) and [javapoet](https://github.com/square/javapoet). – Gaʀʀʏ Feb 12 '18 at 16:39

0 Answers0