oktatas:programozas:java:java_json:jackson-databind
Tartalomjegyzék
Java JSON - Jackson-Databind
- Szerző: Sallai András
- Copyright © 2023, Sallai András
- Web: https://szit.hu
Beszerzés
Maven függőségek:
<dependencies> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.15.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency> </dependencies>
JSON
- emp.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
- Birth.java
import java.time.LocalDate; public class Birth { public String place; public LocalDate date; }
- Employee.java
public class Employee { public int id; public String name; public String city; public Birth birth; public Employee() { } }
- Conv.java
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<Employee> empList = om.readValue(new File("emp.json"), ct); System.out.println(empList.get(0).birth.date); } }
oktatas/programozas/java/java_json/jackson-databind.txt · Utolsó módosítás: 2023/06/15 15:45 szerkesztette: admin