我正在尝试编写一个工具,它将从用户那里获取 json 模式,他们可以在其中指定他们想要提取 json 并保存它的属性。
我发现使用 jsonschema 和 jsonschema2pojo,我可以从模式和 json 生成 pojo,但我不想在所有 100 个实例中创建文件,而是我想创建内存类并将我的 json 转换为该类.
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);
在此之后我被卡住了,如何将其转换为 List here
List<ClassName> classNames = GSON.fromJson(responseData, new TypeRef<List<ClassName>>(){}.getType());
有没有其他方法可以实现这一目标?我什至不在乎有一个中间的java pojo,如果我直接从json中获取json模式中指定的结构,我很好。