Read json from URL in java - using Jackson

Maven dependency -

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
Or Download - bundle (1.3 MB) 

If you are beginner don't worry learn how to Create new Maven project - In 2 minutes

We will Read json from URL in java >

FYI
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

Read json from URL in java - using Jackson Api

package done;

import java.io.IOException;
import java.net.URL;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToJavaObject {

    public static void main(String[] args) {
          try {
                 ObjectMapper objectMappernew ObjectMapper();

                 TempClass tempClassobjectMapper.readValue(new URL("https://jsonplaceholder.typicode.com/todos/1"), TempClass.class);
         System.out.println(tempClass);
        

          catch (JsonGenerationException e) {
                 e.printStackTrace();
          catch (JsonMappingException e) {
                 e.printStackTrace();
          catch (IOException e) {
                 e.printStackTrace();
          }
    }

}

class TempClass{
    private int userId;
    private int id;
    private String title;
    private String completed;
   
    @Override
    public String toString() {
          return "TempClass [userId="userId", id="id", title="title", completed="completed"]";
    }
    public int getUserId() {
          return userId;
    }
    public void setUserId(int userId) {
          this.userIduserId;
    }
    public int getId() {
          return id;
    }
    public void setId(int id) {
          this.idid;
    }
    public String getTitle() {
          return title;
    }
    public void setTitle(String title) {
          this.titletitle;
    }
    public String getCompleted() {
          return completed;
    }
    public void setCompleted(String completed) {
          this.completedcompleted;
    }
}

//output
/*

TempClass [userId=1, id=1, title=delectus aut autem, completed=false]

*/

Related links >

1. Jackson JSON -

We can use Jackson api for for processing JSON in java.

Jackson JSON examples


2. Java provides API (JSR 353) for Processing  JSON (JSR 353).
It provides -
  • Object Model API
  • Streaming API

Java API for JSON processing examples >



3. Simple  (simple.JSONObject)



4. Google Gson - processing java json


Must read for you :