Skip to content

Instantly share code, notes, and snippets.

@petehouston
Created April 6, 2018 09:50
Show Gist options
  • Select an option

  • Save petehouston/2aa9cd8e630d6d6b72a738d3ce15d5b2 to your computer and use it in GitHub Desktop.

Select an option

Save petehouston/2aa9cd8e630d6d6b72a738d3ce15d5b2 to your computer and use it in GitHub Desktop.
Parse JSON in Java using Jackson
public class Article {
private String title;
private String author;
private String url;
private List<String> tags;
public Article() {
}
public Article(String title, String author, String url, List<String> tags) {
this.title = title;
this.author = author;
this.url = url;
this.tags = tags;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<String> getTags() {
return tags;
}
@Override
public String toString() {
return "Article{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", url='" + url + '\'' +
", tags=" + String.join(", ", tags) +
'}';
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class ParseJsonDemo {
public static void main(String ... args) {
String jsonArticle = "{" +
"\"title\": \"Simple guide to parse JSON in Java\"," +
"\"author\": \"Pete Houston\"," +
"\"url\": \"https://blog.petehouston.com\"," +
"\"tags\": [\"json\", \"java\", \"gson\", \"jackson\"]" +
"}";
ObjectMapper mapper = new ObjectMapper();
Article article = null;
try {
article = mapper.readValue(jsonArticle, Article.class);
} catch (IOException e) {
e.printStackTrace();
}
}
}
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment