杰克逊,JsonProperty可以重命名属性对象吗?

时间:2018-10-27 17:43:02

标签: java json spring maven jackson

我正在尝试将JSON反序列化为Java对象Members,然后将其添加到我的数据库中。我使用Spring Maven。

我创建了Java对象,但是必须重命名对象的属性名称才能将其插入数据库中。这就是为什么我使用@JsonProperty。它不起作用,我认为杰克逊被滥用了。

我的Java类Members具有属性cipidMemberStatuslastNamefirstNameemail

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...
}

对于我的数据库,字段应命名为cipid_member_statuslast_namefirst_nameemail。这就是我输入的@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具有属性字段cipidMemberStatuslastNamefirstNameemail,因此最后一行不是工作。 我不知道该怎么办。任何帮助将不胜感激,谢谢。

此外,这里是我的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>

0 个答案:

没有答案