TechieClues TechieClues
Updated date May 21, 2024
This blog explores converting JSON to Java objects in Java. From manual parsing to using popular libraries like Jackson and Gson, and the standardized JSON-B API.

Method 1: Manual Parsing

import org.json.JSONObject;

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

        // Manual parsing using JSONObject
        JSONObject jsonObject = new JSONObject(json);
        String name = jsonObject.getString("name");
        int age = jsonObject.getInt("age");
        String city = jsonObject.getString("city");

        // Create Java object
        Person person = new Person(name, age, city);

        // Output
        System.out.println(person);
    }
}

Output:

Person{name='John', age=30, city='New York'}

Method 2: Jackson Library

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) throws IOException {
        // Sample JSON data
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        // Using Jackson for JSON to Object conversion
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(json, Person.class);

        // Output
        System.out.println(person);
    }
}

Output:

Person{name='John', age=30, city='New York'}

Method 3: Gson Library

import com.google.gson.Gson;

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

        // Using Gson for JSON to Object conversion
        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);

        // Output
        System.out.println(person);
    }
}

Output:

Person{name='John', age=30, city='New York'}

Method 4: JSON-B (Java API for JSON Binding)

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

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

        // Using JSON-B for JSON to Object conversion
        Jsonb jsonb = JsonbBuilder.create();
        Person person = jsonb.fromJson(json, Person.class);

        // Output
        System.out.println(person);
    }
}

Output:

Person{name='John', age=30, city='New York'}

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!