Google GSON library
Let’s assume you have a class Book with just a title.
1 2 3 4 5 6 7 |
private class Book { public String title; public Book(String title) { this.title = title; } } |
Create maven project and add dependencies.
1 2 3 4 5 |
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> |
Then write this code to transform JSON into class:
1 2 3 4 5 6 |
Gson g = new Gson(); Book book = g.fromJson("{\"title\": \"Effective Java\"}", Book.class); System.out.println(book.title); //Effective Java System.out.println(g.toJson(book)); // {"title":"Effective Java"} |
JSON-java library
If need simply get an attribute, you can try org.json
Maven dependencies for library
1 2 3 4 5 |
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency> |
Java code to parse:
1 2 3 |
JSONObject obj = new JSONObject("{\"title\": \"Effective Java\"}"); System.out.println(obj.getString("title")); //Effective Java |