[[oktatas:programozás:java:java_json|< Java JSON]]
====== Java JSON - Jackson-Databind ======
* **Szerző:** Sallai András
* Copyright (c) 2023, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== Beszerzés =====
Maven függőségek:
com.fasterxml.jackson.datatype
jackson-datatype-jsr310
2.15.2
com.fasterxml.jackson.core
jackson-databind
2.15.2
===== JSON =====
[
{
"id": 1,
"name": "Parlag Ferenc",
"city": "Szeged",
"birth": {
"place": "Szeged",
"date": "2001-05-18"
}
},
{
"id": 2,
"name": "Erős István",
"city": "Szeged",
"birth": {
"place": "Szeged",
"date": "2000-03-25"
}
}
]
===== Program =====
import java.time.LocalDate;
public class Birth {
public String place;
public LocalDate date;
}
public class Employee {
public int id;
public String name;
public String city;
public Birth birth;
public Employee() {
}
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class Conv {
public void conv() {
try {
tryConv();
}catch(StreamReadException e) {
System.err.println("Hiba! A folyam olvasása sikertelen!");
}catch(DatabindException e) {
System.err.println("Hiba! A csatolás sikertelen!");
System.err.println(e.getMessage());
}catch(IOException e) {
System.err.println("Hiba! A beolvasás sikertelen!");
}
}
public void tryConv() throws IOException {
ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
CollectionType ct = om.getTypeFactory()
.constructCollectionType(ArrayList.class, Employee.class);
ArrayList empList = om.readValue(new File("emp.json"),
ct);
System.out.println(empList.get(0).birth.date);
}
}
public class App
{
public static void main( String[] args )
{
new Conv().conv();
}
}