我正在尝试将JSON反序列化为Java对象Members
,然后将其添加到我的数据库中。我使用Spring Maven。
我创建了Java对象,但是必须重命名对象的属性名称才能将其插入数据库中。这就是为什么我使用@JsonProperty
。它不起作用,我认为杰克逊被滥用了。
我的Java类Members
具有属性cip
,idMemberStatus
,lastName
,firstName
,email
:
import com.fasterxml.jackson.annotation.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "members")
@JsonPropertyOrder({"cip_etudiant", "nom", "prenom"})
@JsonIgnoreProperties({"app","cote_r","departement","inscription", "profil_id", "programme","trimestre_id", "unit_id","idMemberStatus"})
public class Members {
@Id
@JsonAlias("cip_etudiant")
@JsonProperty("cip")
private String cip;
@JsonProperty("id_member_status")
private int idMemberStatus;
@JsonAlias("nom")
@JsonProperty("last_name")
private String lastName;
@JsonAlias("prenom")
@JsonProperty("first_name")
private String firstName;
@JsonAlias("courriel")
@JsonProperty("email")
private String email;
public Members() {}
public Members(String cip, int idMemberStatus, String lastName, String firstName, String email) {
this.cip = cip;
this.idMemberStatus = idMemberStatus;
this.lastName = lastName;
this.firstName = firstName;
this.email = email;
}
... getters and setters...
}
对于我的数据库,字段应命名为cip
,id_member_status
,last_name
,first_name
和email
。这就是我输入的@JsonProperty
。
这是我如何反序列化Json:
@Bean
public CommandLineRunner runner(MembersDao repository) throws IOException{
return (args) -> {
InputStream data = new FileInputStream("test.json");
ObjectMapper mapper = new ObjectMapper();
List<Members> members = mapper.readValue(data, new TypeReference<List<Members>>(){});
Iterator<Members> iterator = members.iterator();
while (iterator.hasNext()){
Members m = iterator.next();
if (m.getEmail()==null) m.setEmail("test");
m.setIdMemberStatus(1);
}
repository.saveAll(members);
};
}
但是由于members
具有属性字段cip
,idMemberStatus
,lastName
,firstName
,email
,因此最后一行不是工作。
我不知道该怎么办。任何帮助将不胜感激,谢谢。
此外,这里是我的Maven依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.7</version>
</dependency>