Home Java javaTutorial Group and unmarshal data objects using the new Records class in Java 13

Group and unmarshal data objects using the new Records class in Java 13

Jul 31, 2023 pm 11:33 PM
data object java records Grouping and ungrouping

Use the new Records class in Java 13 to marshal and unmarshal data objects

As Java continues to evolve, each new version will introduce some new features and improvements. In Java 13, a new Records class was introduced, which provides us with a concise way to declare and use immutable data objects. In this article, we will introduce the usage of the Records class and demonstrate through some sample code how to use the Records class to marshal and unmarshal data objects.

First, let us understand the concept of Records class. The Records class is a new type that is both a class and an interface and is used to declare immutable data objects. The Records class provides default implementations, including methods such as equals(), hashCode(), and toString(). In addition, the Records class automatically creates a constructor for initializing records. Unlike ordinary classes, the Records class cannot be extended and is not allowed to define its own fields and methods.

Let us give a simple example to illustrate the usage of Records class. Suppose we have a Person object that contains name and age.

public record Person(String name, int age) {}
Copy after login

The above code defines a Person class, which is declared using the Records class. The Person class has two fields: name and age. Now we can create a Person object and access its fields.

Person person = new Person("Alice", 30);
System.out.println(person.name()); // 输出:Alice
System.out.println(person.age()); // 输出:30
Copy after login

As shown above, we can obtain the field value of the Person object through the accessor methods (name() and age()). In addition, the Records class also provides a default toString() method so that we can print the Person object directly.

Next, let’s look at a more complex example. Suppose we have a Student object that extends the Person object and adds the school field.

public record Student(String name, int age, String school) implements Person {}
Copy after login

The above code defines a Student class, which inherits from the Person class and adds a school field. At the same time, we use the implements keyword to specify that the Student class is the implementation class of the Person interface. Objects declared using the Records class can undergo class inheritance and interface implementation just like ordinary objects.

Now, let’s take a look at how to marshal and unmarshal data objects using the Records class. Suppose we want to convert the Person object to a JSON string and save it to a file.

import com.fasterxml.jackson.databind.ObjectMapper;

public class PersonSerialization {
    public static void main(String[] args) throws Exception {
        Person person = new Person("Alice", 30);
        
        // 编组为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(person);
        
        // 保存为文件
        FileWriter writer = new FileWriter("person.json");
        writer.write(jsonString);
        writer.close();
        
        System.out.println("Person对象已编组为JSON并保存到文件中");
    }
}
Copy after login

The above code uses the ObjectMapper class in the Jackson library to marshal Person objects into JSON strings and save them to a file. By calling the mapper.writeValueAsString(person) method, we can convert the Person object into a JSON string. We then use the FileWriter class to write the JSON string to the file.

The process of unmarshaling is the opposite of marshalling. Suppose we read a JSON string from a file and unmarshal it into a Person object.

import com.fasterxml.jackson.databind.ObjectMapper;

public class PersonDeserialization {
    public static void main(String[] args) throws Exception {
        // 从文件中读取JSON字符串
        String jsonString = Files.readString(Path.of("person.json"));
        
        // 解组为Person对象
        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(jsonString, Person.class);
        
        System.out.println("JSON已解组为Person对象:" + person);
    }
}
Copy after login

The above code uses the Files class to read JSON strings from files, and uses the ObjectMapper class to unmarshal the JSON strings into Person objects. By calling the mapper.readValue(jsonString, Person.class) method, we can convert the JSON string into a Person object.

In summary, we have learned about the usage of the new Records class in Java 13, and demonstrated through sample code how to use the Records class to marshal and unmarshal data objects. The Records class provides us with a concise way to declare and use immutable data objects, making the code more readable and reliable. If you are using Java 13 or higher, give the Records class a try and apply it to your project.

The above is the detailed content of Group and unmarshal data objects using the new Records class in Java 13. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles