Technology Encyclopedia Home >How to use JSON in Java?

How to use JSON in Java?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is often used for transmitting data in web applications.

In Java, you can use JSON by using libraries such as Jackson, Gson, or org.json.

Here's a simple example using Jackson:

Firstly, you need to add Jackson dependency in your Maven pom.xml file:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

Then you can use it like this:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(jsonString, Person.class);

        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;

    // getters and setters here...
}

In this example, we're using Jackson's ObjectMapper to convert a JSON string into a Java object.

If you're working on a project that involves a lot of JSON data processing, you might find the cloud services provided by Tencent Cloud very helpful. For instance, Tencent Cloud's API Gateway can help you manage, secure and monitor your APIs, and can handle JSON data format seamlessly.