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

How to Map a JSON Object Array of Pets to a Java POJO?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 01:56:11617browse

How to Map a JSON Object Array of Pets to a Java POJO?

Mapping a JSON Object Array to a Java POJO

Given a JSON object with an owner's name and an array of pets, how would you map it to a POJO (Plain Old Java Object)?

JSON Object

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

POJO Mapping

To convert the JSON object into a Java POJO, create two classes: Person and Pet.

public class Person {

    private String ownerName;
    private List<Pet> pets;

    // Getters and Setters
}

public class Pet {

    private String name;

    // Getter and Setter
}

In the Person class, ownerName is a string and pets is a list of Pet objects. Each Pet object has a name property. This mapping accurately reflects the structure of the JSON object.

The above is the detailed content of How to Map a JSON Object Array of Pets 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