search
HomeJavajavaTutorialHow to convert JSON array to Java object in Java?

How to convert JSON array to Java object in Java?

Sep 06, 2023 am 11:09 AM
javajsonobjectarrayConvert

How to convert JSON array to Java object in Java?

How to convert JSON array to Java object in Java?

JSON (JavaScript Object Notation) is a lightweight data exchange format that is widely used in front-end and back-end data transmission and storage. In Java, we usually use third-party libraries to parse and build JSON data. This article will introduce how to use the JSON library to convert a JSON array into a Java object and provide corresponding code examples.

Before processing JSON data, we need to introduce the JSON library first. Here we use Google's Gson library, which is an open source and powerful Java JSON library. You can introduce the Gson library by adding the following dependency in pom.xml (Maven) or build.gradle (Gradle):

<!-- Maven -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
// Gradle
implementation 'com.google.code.gson:gson:2.8.6'

Next, we will provide a simple JSON array example:

[
   {
      "name": "John",
      "age": 25,
      "city": "New York"
   },
   {
      "name": "Alice",
      "age": 28,
      "city": "London"
   },
   {
      "name": "Bob",
      "age": 30,
      "city": "Tokyo"
   }
]

The following are the steps and code examples to convert a JSON array to a Java object:

1. Create a Java class

First, we need to create a Java class to Represents data in a JSON array. Each object should contain fields corresponding to JSON keys. In this example, we create a Java class named Person, containing name, age and city fields:

public class Person {
    private String name;
    private int age;
    private String city;

    // getter and setter methods
}

2. Parse the JSON array

Next, We will parse JSON array by using Gson library. First, we need to create a Gson object:

Gson gson = new Gson();

Then, we can use the fromJson() method to convert the JSON array into an array of Java objects:

String json = "[{...}, {...}, {...}]";  // JSON数组字符串
Person[] persons = gson.fromJson(json, Person[].class);

In this way, each element in the persons array Is a Person object that can be accessed by index.

3. Using Java objects

Now, we can easily access and use the properties of the Person object:

for (Person person : persons) {
    System.out.println(person.getName());
    System.out.println(person.getAge());
    System.out.println(person.getCity());
}

The above is to convert the JSON array Complete code example for Java objects:

import com.google.gson.Gson;

public class JsonArrayToObjectExample {
    public static void main(String[] args) {
        String json = "[{"name":"John","age":25,"city":"New York"},{"name":"Alice","age":28,"city":"London"},{"name":"Bob","age":30,"city":"Tokyo"}]";

        Gson gson = new Gson();
        Person[] persons = gson.fromJson(json, Person[].class);

        for (Person person : persons) {
            System.out.println(person.getName());
            System.out.println(person.getAge());
            System.out.println(person.getCity());
        }
    }
}

class Person {
    private String name;
    private int age;
    private String city;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

Through the above steps, we can convert JSON arrays into Java objects and use these objects conveniently in the code. Using the Gson library can help us simplify the parsing process of JSON data and improve the readability and maintainability of the code.

Hope this article can help you understand how to convert JSON array to Java object in Java!

The above is the detailed content of How to convert JSON array to Java object in Java?. 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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.