Home >Java >javaTutorial >How to Convert a JSON Array of Objects into Java POJOs?

How to Convert a JSON Array of Objects into Java POJOs?

DDD
DDDOriginal
2024-12-06 12:52:15577browse

How to Convert a JSON Array of Objects into Java POJOs?

Converting Array of JSON Object to Java POJO

Question:

Convert the provided JSON object into a Java POJO class. Determine the mapping for attributes and their types.

JSON Object:

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

Answer:

To convert such JSON objects to Java POJOs, it is recommended to use tools like www.jsonschema2pojo.org. Here's a step-by-step guide using this tool:

Instructions:

  1. Visit www.jsonschema2pojo.org.
  2. Select "Java" as the target language.
  3. Select "JSON" as the source.
  4. Paste your JSON object into the "Schema" field.
  5. If desired, adjust the annotation style and other optional settings.
  6. Click the "Preview" button.

Example:

For the provided JSON object, the tool generates the following POJO classes:

Person Class:

public class Person {

 private String ownerName;
 private List<Pet> pets = null;

 // getters and setters
}

Pet Class:

public class Pet {

 private String name;

 // getters and setters
}

Note:

The mapping adheres to Java naming conventions, converting JSON property names to camelCase and assuming pet attributes are organized within a "pets" field in the JSON object.

The above is the detailed content of How to Convert a JSON Array of Objects into Java POJOs?. 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