<dependency> <groupId>org.apache.johnzon</groupId> <artifactId>johnzon-core</artifactId> <version>1.2.10</version> </dependency> import javax.json.bind.annotation.JsonbProperty; public class Person { @JsonbProperty("name") private String firstName; @JsonbProperty("age") private int age; public Person(String firstName, int age) { this.firstName = firstName; this.age = age; } // Getters and Setters } import org.apache.johnzon.mapper.MapperBuilder; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class JsonSerializationExample { public static void main(String[] args) { // Create a person object Person person = new Person("John", 30); // Serialize the person object to JSON Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(person); // Write the JSON data to a file try (FileWriter fileWriter = new FileWriter("person.json")) { fileWriter.write(json); } catch (IOException e) { e.printStackTrace(); } // Read the JSON data from the file and deserialize it to a person object try { byte[] jsonData = Files.readAllBytes(Paths.get("person.json")); Person deserializedPerson = jsonb.fromJson(new String(jsonData), Person.class); System.out.println("Name: " + deserializedPerson.getFirstName()); System.out.println("Age: " + deserializedPerson.getAge()); } catch (IOException e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文