Rick

Rick
Rick

Tuesday, February 17, 2015

How to Parse JSON to from Java Object using Boon Example

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.
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.

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.



QBit the microservice framework for java




No comments:

Post a Comment

Kafka and Cassandra support, training for AWS EC2 Cassandra 3.0 Training