我正在编写一些需要使用对象的 JSON 元数据的东西。
例如给定下面的示例类:
public class MyClassA
{
@JsonProperty("a")
private String a;
@JsonProperty("anothername")
private Integer b;
@JsonProperty("c")
private MyClassB c;
}
public class MyClassB
{
private Integer z = -1;
@JsonValue
public Integer toInteger()
{
return z;
}
}
我想知道 MyClassA 映射到以下属性名称和 JSON 原始类型:(a - 字符串,另一个名称 - 数字,c - 数字)而不做 Jackson 可能正在做的相同内省(introspection)。
Jackson 下的哪些 API 可用于执行此操作并不是很明显。
最佳答案
您正在寻找的是描述您的 JSON 的模式。有一个 jackson module就为了这个。它可以像下面这样使用:
对象:
class Entity {
private Long id;
private List<Profile> profiles;
// getters/setters
}
class Profile {
private String name;
private String value;
// getters / setters
}
生成模式的代码:
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(Entity.class, visitor);
JsonSchema schema = visitor.finalSchema();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
}
}
输出:
{
"type" : "object",
"properties" : {
"id" : {
"type" : "integer"
},
"profiles" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"value" : {
"type" : "string"
}
}
}
}
}
}
关于java - 使用 Jackson 提取 JSON 元数据(原始类型和名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22487138/