我有 json 文件 其中包含 json 对象 作为内部属性的值:
{
"name": "name",
"json": {...}
}
我需要在RestController中自动获取它,并将其用作JPA+Hibernate中的实体。
我的实体是:
更新 -> 更具体的实体
@Entity
@Table(name = "collections")
public class Collection {
@Id
private String name;
@Column(name = "cache_limit")
private int limit;
@Column(name = "cache_algorithm")
private String algorithm;
@Transient
private JsonNode schema;
@JsonIgnore
@Column(name ="json_schema")
private String jsonSchema;
public Collection() {
}
public String getJsonSchema() {
return schema.toString();
}
public void setJsonSchema(String jsonSchema) {
ObjectMapper mapper = new ObjectMapper();
try {
schema = mapper.readTree(jsonSchema);
} catch (IOException e) {
throw new RuntimeException("Parsing error -> String to JsonNode");
}
}
..setters and getters for name limit algorithm schema..
}
当我使用 entityManager.persist(Collection)
时,我的 json_schema
列为 NULL
我该如何解决它?问题可能出在setJsonSchema()
更新:
public String getJsonSchema() {
return jsonSchema;
}
public void setJsonSchema(JsonNode schema) {
this.jsonSchema = schema.toString();
}
这样的 getter/setter 并不能解决问题
最佳答案
您可以将 JsonNode json
属性定义为 @Transient
,这样 JPA 就不会尝试将其存储在数据库中。但是,jackson 应该能够将其来回翻译为 Json。
然后您可以为 JPA 编写 getter/setter 代码,这样您就可以从 JsonNode 来回转换为 String。您定义一个 getter getJsonString
,将 JsonNode json
转换为 String
。该列可以映射到表列,例如“json_string”,然后定义一个 setter,在其中从 JPA 接收 String
并将其解析为 Jackson 可用的 JsonNode。
不要忘记将 @JsonIgnore
添加到 getJsonString
,这样 Jackson 就不会尝试将 json 转换为 jsonString。
@Entity
@Table(name = "cats")
public class Cat {
private Long id;
private String name;
@Transient
private JsonNode json;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
@Column(name ="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setId(Long id) {
this.id = id;
}
// Getter and setter for name
@Transient
public JsonNode getJson() {
return json;
}
public void setJson(JsonNode json) {
this.json = json;
}
@Column(name ="jsonString")
public String getJsonString() {
return this.json.toString();
}
public void setJsonString(String jsonString) {
// parse from String to JsonNode object
ObjectMapper mapper = new ObjectMapper();
try {
this.json = mapper.readTree(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于java - 如何使用 Jackson 自动解析 Spring Boot 应用程序中的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975002/