Reputation: 817
given a JSON-annotated Java class, I am looking for some utility to get its type information.
For example having below class structure:
class A extends B {
@JsonIgnore
int _some_internal_field;
int f1;
C f2;
}
class B {
boolean f3;
String f4;
}
class C {
float f5;
}
I would like to call
System.out.println(
jsonTypeInfoFrom(A.class)
.toString());
and get:
{
"f1": "int",
"f2": {
"f5": "float"
},
"f3": "boolean",
"f4": "string"
}
Where I can find such a jsonTypeInfoFrom(Class)
method? Looked into Jackson itself, but could not find one (yet).
Please help :)
Adrian.
Upvotes: 0
Views: 71
Reputation: 652
You can use jacksin-module-jsonSchema library. you can add the library using the folowing dependency:
> <dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>2.9.5</version>
</dependency>
and here is a sample code for generating json schema from java class:
SchemaFactoryWrapper schemaFactory = new SchemaFactoryWrapper(); ObjectMapper mapper = new ObjectMapper(); mapper.acceptJsonFormatVisitor(Entity.class, schemaFactory); JsonSchema resultSchema = schemaFactory.finalSchema(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultSchema));
Upvotes: 1
Reputation: 401
//Use refelcting Api to get the declared fields and create the json schema using HashMap
public static String getJsonSchema(Class clazz) throws IOException {
Field[] fields = clazz.getDeclaredFields();
List<Map<String,String>> map=new ArrayList<Map<String,String>>();
for (Field field : fields) {
HashMap<String, String> objMap=new HashMap<String, String>();
objMap.put("name", field.getName());
objMap.put("type", field.getType().getSimpleName());
objMap.put("format", "");
map.add(objMap);
}
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
return json;
}
Upvotes: 0