How to Parse JSON to from Java Object using Boon Example
In this example you will learn how to parse a JSON String to Java and how to convert Java Object to JSON format using Boon.
This is a parody of How to Parse JSON to from Java Object .
JSON, JavaScript Object notation, is an object notation. JSON is also valid JavaScript object notation. It is used as an interchange format. Because it is small and compact, it is often used in place of XML. JSON is also featured prominently as a interchange format in Microservices due to its tolerant reader and promiscuous writer features. JSON is schema-less.
Java does not have any built-in support to parse JSON but there is a JSON JSR for parsing JSON so expect it soon. Java developers have choice when picking a JSON parsing lib: GSON, Jackson, JSON-simple, and of course Boon which also is the built-in parser for Groovy and is a standalone project focusing on reflection, JSON path, object querying and more.
Boon is a very very high performance JSON parser among other things. It has no external dependency and solely depends on the JDK. Boon JSON has a similar interface as Jackson and GSON.
Boon JSON is also powerful and provides full binding support for common JDK classes as well as any Java Bean class, e.g. Player in our case. It also provides data binding for Java Collection classes e.g. Map as well Enum.
Let's get started.
Boon Library
The complete Boon library consists of 1 jar file that are used for many diffident operation. I am going to assume that you use maven, gradle, or their ilk.
<dependency>
<groupId>io.fastjson</groupId>
<artifactId>boon</artifactId>
<version>0.31</version>
</dependency>
You DO NOT need Default Constructor in Your Bean Class
When I first run my program, it just worked because I used Boon damn it.
Converting an object to JSON
Player kevin = new Player("Kevin", "Cricket", 32, 221,
new int[]{33, 66, 78, 21, 9, 200});
final String json = toJson(kevin);
puts("JSON", json);
Reading an object from JSON
Player somePlayer = fromJson(json, Player.class);
puts("They are equal", somePlayer.equals(kevin));
JSON {"name":"Kevin","sport":"Cricket",
"age":32,"id":221,"lastScores":[33,66,78,21,9,200]}
They are equal true
Boon can mimic the Jackson interface or the GSON interface
Player kevin = new Player("Kevin", "Cricket", 32, 221,
new int[]{33, 66, 78, 21, 9, 200});
final ObjectMapper mapper = JsonFactory.create();
final File file = File.createTempFile("json", "exmaple.json");
mapper.writeValue(file, kevin);
Player somePlayer = mapper.readValue(file, Player.class);
puts("They are equal", somePlayer.equals(kevin));
This will also create a temp file in a temp folder which will be deleted by the OS because who would want stray json files all over their hard disk.
Here is the player POJO.
Here is the player POJO.
Player POJO
public class Player {
private final String name;
private final String sport;
private final int age;
private final int id;
private final int[] lastScores;
public Player(String name, String sport, int age, int id, int[] lastScores) {
this.name = name;
this.sport = sport;
this.age = age;
this.id = id;
this.lastScores = lastScores;
}
public final String getName() {
return name;
}
public final String getSport() {
return sport;
}
public final int getAge() {
return age;
}
public final int getId() {
return id;
}
public final int[] getLastScores() {
return lastScores;
}
@Override
public String toString() {
return "Player{" +
"name='" + name + '\'' +
", sport='" + sport + '\'' +
", age=" + age +
", id=" + id +
", lastScores=" + Arrays.toString(lastScores) +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
if (age != player.age) return false;
if (id != player.id) return false;
if (!Arrays.equals(lastScores, player.lastScores)) return false;
if (name != null ? !name.equals(player.name) : player.name != null) return false;
if (sport != null ? !sport.equals(player.sport) : player.sport != null) return false;
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (sport != null ? sport.hashCode() : 0);
result = 31 * result + age;
result = 31 * result + id;
result = 31 * result + (lastScores != null ? Arrays.hashCode(lastScores) : 0);
return result;
}
}
Complete example
package com.examples;
import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;
import java.io.File;
import java.util.Arrays;
import static org.boon.Boon.fromJson;
import static org.boon.Boon.puts;
import static org.boon.Boon.toJson;
/**
* Created by rhightower on 2/17/15.
*/
public class HowToParseJSONInJava {
public static class Player {
private final String name;
private final String sport;
private final int age;
private final int id;
private final int[] lastScores;
public Player(String name, String sport, int age, int id, int[] lastScores) {
this.name = name;
this.sport = sport;
this.age = age;
this.id = id;
this.lastScores = lastScores;
}
public final String getName() {
return name;
}
public final String getSport() {
return sport;
}
public final int getAge() {
return age;
}
public final int getId() {
return id;
}
public final int[] getLastScores() {
return lastScores;
}
@Override
public String toString() {
return "Player{" +
"name='" + name + '\'' +
", sport='" + sport + '\'' +
", age=" + age +
", id=" + id +
", lastScores=" + Arrays.toString(lastScores) +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
if (age != player.age) return false;
if (id != player.id) return false;
if (!Arrays.equals(lastScores, player.lastScores)) return false;
if (name != null ? !name.equals(player.name) : player.name != null) return false;
if (sport != null ? !sport.equals(player.sport) : player.sport != null) return false;
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (sport != null ? sport.hashCode() : 0);
result = 31 * result + age;
result = 31 * result + id;
result = 31 * result + (lastScores != null ? Arrays.hashCode(lastScores) : 0);
return result;
}
}
public static void main1(String... args) {
Player kevin = new Player("Kevin", "Cricket", 32, 221, new int[]{33, 66, 78, 21, 9, 200});
final String json = toJson(kevin);
puts("JSON", json);
Player somePlayer = fromJson(json, Player.class);
puts("They are equal", somePlayer.equals(kevin));
}
public static void main(String... args) throws Exception{
Player kevin = new Player("Kevin", "Cricket", 32, 221,
new int[]{33, 66, 78, 21, 9, 200});
final ObjectMapper mapper = JsonFactory.create();
final File file = File.createTempFile("json", "exmaple.json");
mapper.writeValue(file, kevin);
Player somePlayer = mapper.readValue(file, Player.class);
puts("They are equal", somePlayer.equals(kevin));
}
}
This will also create a temp file in a temp folder which will be deleted by the OS because who would want stray json files all over their hard disk.
That's all about how to parse JSON String in Java and convert a Java object to JSON using Boon. Though there are couple of more good open source library available for JSON parsing and conversion e.g. GSON and JSON-Simple but Boon is one of the best and feature rich, its also tried and tested library in many places since it gets included with Groovy. All parsers and mappers have their own caveats. It is best to test.
YourKit
YourKit supports Boon open source project with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit's leading software products: YourKit Java Profiler and YourKit .Net profiler.
- [Detailed Tutorial] QBit microservice example
- [Doc] Queue Callbacks for QBit queue based services
- [Doc] Using QBit microservice lib's HttpClient GET, POST, et al, JSON, Java 8 Lambda
- [Doc] Using QBit microservice lib's WebSocket support
- [Quick Start] Building a simple Rest web microservice server with QBit
- [Quick Start] building a single page web application with QBit
- [Quick Start] Building a TODO web microservice client with QBit
- [Quick Start] Building a TODO web microservice server with QBit
- [Quick Start] Building boon for the QBit microservice engine
- [Quick Start] Building QBit the microservice lib for Java
- [Rough Cut] Delivering up Single Page Applications from QBit Java JSON Microservice lib
- [Rough Cut] Working with event bus for QBit the microservice engine
- [Rough Cut] Working with inproc MicroServices
- [Rough Cut] Working with private event bus for inproc microservices
- [Rough Cut] Working with strongly typed event bus proxies for QBit Java Microservice lib
- [Rough Cut] Working with System Manager for QBit Mircoservice lib
- [Z Blog] Qbit servlet support also a preview of using jetty and the QBit microservice lib together
- [Z Notebook] More benchmarking internal
- [Z Notebook] Performance testing for REST
- [Z Notebook] Roadmap
- Home
- Introduction to QBit
- Local Service Proxies
- QBit Boon New Wave of JSON HTTP and Websocket
- QBit Docs
No comments:
Post a Comment