Maven dependency -
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
|
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
https://jsonplaceholder.typicode.com/todos/1 contains >
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
"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 objectMapper = new ObjectMapper();
TempClass tempClass = objectMapper.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.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCompleted() {
return completed;
}
public void setCompleted(String completed) {
this.completed = completed;
}
}
//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 >