Home >Java >javaTutorial >How to Map a JSON Array of Objects to a Java POJO?

How to Map a JSON Array of Objects to a Java POJO?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 14:53:12705browse

How to Map a JSON Array of Objects to a Java POJO?

Mapping JSON Array of Objects to Java POJO

Converting a JSON object containing an array of objects to a Java POJO (Plain Old Java Object) requires understanding the structure of the JSON and defining corresponding properties and data types in the POJO class.

Let's consider the following JSON snippet:

{
    "ownerName": "Robert",
    "pets": [
        {
            "name": "Kitty"
        },
        {
            "name": "Rex"
        },
        {
            "name": "Jake"
        }
    ]
}

To map this JSON to a Java POJO, we need to create a class with the following properties:

public class Person {
    private String ownerName;
    private List<Pet> pets;
}

public class Pet {
    private String name;
}

The Person class will have a String property called ownerName to hold the owner's name. It will also have a List property called pets to hold the list of pet objects.

The Pet class will have a single String property called name to hold the pet's name.

To generate these POJO classes automatically, you can use a tool like jsonschema2pojo.org. This tool allows you to specify the JSON schema or JSON object and generate corresponding POJO classes.

For simple JSON schemas, it is also possible to manually write the POJO classes by examining the structure of the JSON object. This approach is less error-prone than using automated tools but can be more time-consuming.

In the case of the provided JSON, the generated POJO classes would look like the example shown in the answer, with the Person class having the ownerName and pets properties, and the Pet class having the name property.

The above is the detailed content of How to Map a JSON Array of Objects to a Java POJO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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