Skip to content

Instantly share code, notes, and snippets.

@petehouston
Created April 6, 2018 09:48
Show Gist options
  • Save petehouston/95d03b9409c416d6cd985b5fa2f35033 to your computer and use it in GitHub Desktop.
Save petehouston/95d03b9409c416d6cd985b5fa2f35033 to your computer and use it in GitHub Desktop.
Parse JSON in Java using Gson
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) +
'}';
}
}
package com.petehouston.coding.java.parsejson;
import com.google.gson.Gson;
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\"]" +
"}";
Gson gson = new Gson();
Article article = gson.fromJson(jsonArticle, Article.class);
System.out.println(article);
}
}
<!-- add this into your pom.xml -->
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment