Easily Map JSON Responses to Java Classes with Java HttpClient

06 May 2023 Balmiki Mandal 0 Core Java

Mapping JSON Response to Java Class with Apache HttpClient

JSON responses from web services can be tricky to parse and map to a Java class. In this tutorial, we will show you how to use Apache HttpClient to map a JSON response to a Java object. We’ll provide code snippets and sample applications for each step.

The JSON Object

For this example, let’s assume that we have the following JSON Response:

{
  "name": "John Smith", 
  "age": 25,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY"
  }
}

Creating the Java Class

The first step is to create a Java class to map the JSON response to. For our example, we’ll call it Person. Person will have three properties: name, age, and address. The address property also needs to be a class that maps to the address property of the JSON response.

public class Person {
  private String name;
  private int age;
  private Address address;

  // getters and setters ommitted
}

public class Address {
  private String street;
  private String city;
  private String state;
  
  // getters and setters ommitted 
}

Creating the Http Client Request/Response

Next, we need to create the HttpClient request/response that will return the JSON response. We’ll use the Apache HttpClient library for this.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://example.com/person");
HttpResponse response = httpClient.execute(request);

Mapping the JSON Response to the Java Class

Now that we have the response, we need to parse the JSON and map it to our Person class. To do this, we’ll use the Gson library from Google. Gson provides a simple way to parse a JSON string and map it to a Java class.

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

And that’s it! We now have a Person object that contains the data from the JSON response. We can use this object to access the data from our response.

Conclusion

In this tutorial, we showed how to map a JSON response to a Java object using Apache HttpClient and Gson. We covered how to parse the JSON response into a Java class and how to use the Gson library to map the JSON to the Java class. With the parsed data in hand, we can now use it to further process the data or store it permanently in our database.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.