Dépendances Jackson
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.0-rc1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0-rc1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.0-rc1</version>
</dependency>
POJO Java
package fr.ronanlefichant.jackson;
public class Person {
private String firstName, lastName;
/* Constructeur vide necessaire pour mapper l'objet*/
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
/* Accesseurs et mutateurs essentiels au bon fonctionnement de Jackson */
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
Exemple
package fr.ronanlefichant.jackson;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws IOException {
/* Conversion de la liste d'objets JSON en liste d'objets Java */
ObjectMapper objectMapper = new ObjectMapper();
String jsonPersonsArray = "[{\"firstName\" : \"Jean\", \"lastName\" : \"Dupond\"}, {\"firstName\" : \"Pierre\", \"lastName\" : \"Dupont\"}]";
List<Person> persons = objectMapper.readValue(jsonPersonsArray, new TypeReference<List<Person>>() {
});
/* Affiche les objets de la liste */
System.out.println(persons);
/* Liste d'objets Java en objets JSON */
objectMapper.writeValue(new File("persons.json"), persons);
/* Liste d'objets Java en liste d'objets JSON dans une chaine de caractères */
String jsonInString = objectMapper.writeValueAsString(persons);
System.out.println(jsonInString);
}
}
Commentaires
Enregistrer un commentaire