Home json How to use Gson to parse a JSON string and convert it...

How to use Gson to parse a JSON string and convert it into a Java object

0

Gson is a Java library developed by Google for parsing and generating JSON. It is a lightweight library with a simple API that makes it easy to work with JSON in Java.

Gson provides a set of classes for data binding, which allow you to convert JSON to and from Java objects. It also provides classes for streaming JSON, for example for parsing large amounts of data or for generating JSON data on the fly.

Gson has a number of features, including support for custom serialization and deserialization, the ability to exclude certain fields from the serialization or deserialization process, and support for serializing and deserializing nested objects. It is widely used in Java-based applications for working with JSON data.

Maven Dependency

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10</version>
</dependency>

Here is an example of how to use Gson to parse a JSON string and convert it into a Java object:

import com.google.gson.Gson;

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

        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);

        System.out.println(person.name);  // Outputs "John"
        System.out.println(person.age);   // Outputs 30
        System.out.println(person.city);  // Outputs "New York"
    }
}

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

To generate a JSON string from a Java object, you can use the toJson method of the Gson class:

import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {
        Person person = new Person("John", 30, "New York");

        Gson gson = new Gson();
        String json = gson.toJson(person);

        System.out.println(json);  // Outputs "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"
    }
}

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

    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
}

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version