This is the sample source code for my blog at https://blog.petehouston.com/simple-guide-to-parse-json-in-java/
Created
April 6, 2018 09:48
-
-
Save petehouston/95d03b9409c416d6cd985b5fa2f35033 to your computer and use it in GitHub Desktop.
Parse JSON in Java using Gson
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) + | |
'}'; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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