Java 将json数组转换为POJO?(单个数组上的代码wrkng)
下面是json对象的数组Java 将json数组转换为POJO?(单个数组上的代码wrkng),java,json,Java,Json,下面是json对象的数组 [ { "name": " hh", "place": "usa", "isPres": false, "id": { "lId": { "id1": "40", "level1": "tte" }, "space": "ua" }, "isempty": null, "isspace": true }, { "name": "
[
{
"name": " hh",
"place": "usa",
"isPres": false,
"id": {
"lId": {
"id1": "40",
"level1": "tte"
},
"space": "ua"
},
"isempty": null,
"isspace": true
},
{
"name": " GE",
"place": "guinea",
"isPres": true,
"id": {
"lId": {
"id1": "30",
"level1": "Le"
},
"space": "ma"
},
"isempty": null,
"isspace": false
}
]
我尝试了以下代码将JSON数组转换为POJO
公共类JsonToPojo{
public static void main(String[] args) {
String packageName="com.vogella.maven.quickstart";
File inputJson= new File("C:/projects/quickstart/input.json");
File outputPojoDirectory=new File("."+File.separator+"convertedPojo");
outputPojoDirectory.mkdirs();
try {
new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Encountered issue while converting to pojo: "+e.getMessage());
e.printStackTrace();
}
}
public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{
JCodeModel codeModel = new JCodeModel();
URL source = inputJson;
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
public SourceType getSourceType(){
return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, className, packageName, source);
codeModel.build(outputPojoDirectory);
}
}
但问题是,我只为数组中的一个对象获取JavaPOJO类,而不是两个对象
我想要两个数组的结果,只是一个建议:如果您使用的是eclipse,您可以使用 从示例JSON自动创建pojo的插件 然后在java代码中,可以使用Jackson mapper
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";
//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);
参考这个