Open In App

Java Boon JSON API

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

JSON objects are throughout available as output for any REST API call and in all mediums, it is the way of communication between any entities. Java Boon is the fastest way to serialize and parse JSON in Java and it is widely used in projects. Necessary jars to use Boon in the project :

boon-0.34.jar

Alternatively, as a maven entry need to add the following in pom.xml

 <dependency>
   <groupId>io.fastjson</groupId>
   <artifactId>boon</artifactId>
   <version>0.34</version>
</dependency>

Example 1: Boon’s ObjectMapper helps for mapping JSON data into plain old Java objects (“POJOs”). By using the puts method, we can easily put the value of an object as JSON

Java




import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;
import static org.boon.Boon.puts;
  
public class GeekAuthor {
    public enum Gender { MALE, FEMALE };
    public static class Name {
        private String firstName, lastName;
  
        public Name( String firstName, String lastName ) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
  
        public String getFirstName() {
            return firstName;
        }
  
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
  
        public String getLastName() {
            return lastName;
        }
  
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
  
          
    }
    private Gender gender;
    private Name name;
    private boolean isActive;
  
    public Name getName() { return name; }
      
    public boolean isActive() {
        return isActive;
    }
  
    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }
  
    public Gender getGender() { return gender; }
  
    public void setName(Name n) { name = n; }
      
    public void setGender(Gender g) { gender = g; }
    public static void main(String args[]) {
        ObjectMapper mapper =  JsonFactory.create();
  
        GeekAuthor geekAuthor = new GeekAuthor();
        geekAuthor.setGender( GeekAuthor.Gender.FEMALE );
        geekAuthor.setName(new GeekAuthor.Name("Geek", "One"));
        geekAuthor.setActive( true );
  
        puts ( mapper.writeValueAsString( geekAuthor ) );
    }
}


Output:

 

Example 2: With Streams, Readers, and Writers

Java




import static org.boon.Boon.puts;
  
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.boon.Lists;
import org.boon.core.Dates;
import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;
  
public class BoonJsonTutorial {
  
    public static class SampleBean {
        String name = "gfg";
  
        @Override
        public String toString() {
            return "SampleBean{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
  
    public static class GeekUser {
        public enum Gender { MALE, FEMALE };
  
        public static class Name {
            private String first, last;
  
            public Name( String _first, String _last ) {
                this.first = _first;
                this.last = _last;
            }
  
            public String getFirst() { return first; }
            public String getLast() { return last; }
            public void setFirst(String s) { first = s; }
            public void setLast(String s) { last = s; }
  
            @Override
            public String toString() {
                return "Name{" +
                        "first='" + first + '\'' +
                        ", last='" + last + '\'' +
                        '}';
            }
        }
  
        private Gender gender;
        private Name name;
        private boolean verified;
        private Date birthDate;
  
        public Name getName() { return name; }
        public boolean isVerified() { return verified; }
        public Gender getGender() { return gender; }
  
        public void setName(Name n) { name = n; }
        public void setVerified(boolean b) { verified = b; }
        public void setGender(Gender g) { gender = g; }
  
        public Date getBirthDate() { return birthDate; }
        public void setBirthDate( Date birthDate ) { this.birthDate = birthDate; }
  
        @Override
        public String toString() {
            return "GeekUser{" +
                    "gender=" + gender +
                    ", name=" + name +
                    ", isVerified=" + verified +
                    '}';
        }
    }
  
  
    public static void example1 () throws Exception {
  
  
        SampleBean myBean = new SampleBean();
        File destination = File.createTempFile("geekuser", ".json");
        ObjectMapper mapper =  JsonFactory.create();
        puts ("json string = ", mapper.writeValueAsString( myBean ));
         
        // where 'dst' can be File, OutputStream or Writer
        mapper.writeValue( destination, myBean ); 
        File src = destination;
          
        // 'src' can be File, InputStream, Reader, String
        SampleBean value = mapper.readValue(src, SampleBean.class); 
        puts ("samplebean = ", value);
        Object root = mapper.readValue(src, Object.class);
        Map<String,Object> rootAsMap =  mapper.readValue(src, Map.class);
        puts ("root = ", root);
        puts ("rootAsMap = ", rootAsMap);
        SampleBean sampleBean1 = new SampleBean(); sampleBean1.name = "GeekPerson1";
        SampleBean sampleBean2 = new SampleBean(); sampleBean2.name = "GeekPerson2";
        destination = File.createTempFile("geekList", ".json");
        final List<SampleBean> list = Lists.list( sampleBean1, sampleBean2 );
        puts ("json string = ", mapper.writeValueAsString( list ));
        mapper.writeValue( destination, list );
        src = destination;
        List<SampleBean> beans = mapper.readValue(src, List.class, SampleBean.class);
        puts ("samplebeans = ", beans);
    }
  
    public static void example2 () throws Exception {
        ObjectMapper mapper =  JsonFactory.create();
        GeekUser user = new GeekUser();
        user.setGender( GeekUser.Gender.MALE );
        user.setName(new GeekUser.Name("Rachel", "Green"));
        user.setVerified( true );
        user.setBirthDate( Dates.getUSDate( 5, 25, 1980 ) );
        puts (mapper.writeValueAsString( user ));
          
        // Now to write and then read this as a file.
        File file = File.createTempFile( "geekuser", ".json" );
        mapper.writeValue( file, user );
        GeekUser userFromFile = mapper.readValue( file, GeekUser.class );
        puts ( "userFromFile = ", userFromFile );
        Path path = Paths.get(file.toString());
        InputStream inputStream = Files.newInputStream(path);
        GeekUser userFromInput = mapper.readValue( inputStream, GeekUser.class );
        puts ( "userFromInput = ", userFromInput );
        Reader reader = Files.newBufferedReader( path, StandardCharsets.UTF_8 );
        GeekUser userFromReader = mapper.readValue( reader, GeekUser.class );
        puts ( "userFromReader = ", userFromReader );
    }
  
    public static void main (String args[]) throws Exception {
        example1();
        example2();
    }
}


Output:

 

Example 3: Let us see with a few samples of how it is 

  • Getting converted to JSON from an object (toJson)
  • By using the converted JSON, how to get the object back(fromJson)
  • JsonParserAndMapper. In this, we can map all/few entries via a mapper
  • Manipulation of the map by using copy

Java




import static org.boon.Boon.puts;
import static org.boon.Exceptions.die;
import static org.boon.Lists.list;
import static org.boon.Maps.copy;
import static org.boon.Maps.fromMap;
import static org.boon.json.JsonFactory.fromJson;
import static org.boon.json.JsonFactory.toJson;
  
import java.util.List;
import java.util.Map;
  
import org.boon.json.JsonParserAndMapper;
import org.boon.json.JsonParserFactory;
  
public class BoonJsonValidation {
  
    public static class GeekEmployee {
        String firstName;
        String lastName;
        List<String> listOfArticles;
  
        public GeekEmployee(String firstName, String lastName, List<String> todo) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.listOfArticles = todo;
        }
  
        @Override
        public String toString() {
            return "GeekEmployee{" +
                    "firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    ", listOfArticles=" + listOfArticles +
                    '}';
        }
  
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof GeekEmployee)) return false;
            GeekEmployee employee = (GeekEmployee) o;
            if (firstName != null ? !firstName.equals(employee.firstName) : employee.firstName != null) return false;
            if (lastName != null ? !lastName.equals(employee.lastName) : employee.lastName != null) return false;
            if (listOfArticles != null ? !listOfArticles.equals(employee.listOfArticles) : employee.listOfArticles != null) return false;
            return true;
        }
  
        @Override
        public int hashCode() {
            int result = firstName != null ? firstName.hashCode() : 0;
            result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
            result = 31 * result + (listOfArticles != null ? listOfArticles.hashCode() : 0);
            return result;
        }
    }
  
  
    public static void  main(String args[]) {
          
        // Happy case - create an employee ad check it
        GeekEmployee geekA = new GeekEmployee("GeekA", "GeekA",
                list("Java Programming!!", "Python Programming"));
        String json = toJson(geekA);
        puts( "geekA json data = ", json );
        puts( "geekA object data = ", geekA );
        GeekEmployee geekB = fromJson(json, GeekEmployee.class);
        boolean ok = geekA.equals(geekB) || die("Both are not equal");
        JsonParserAndMapper mapper = new JsonParserFactory().strict().create();
        
        // Missing List of Articles, not adding them
        Map<String, Object> map = mapper.parseMap("{\"firstName\":\"GeekA\",\"lastName\":\"GeekA\"} ");
  
        // Validate
        boolean hasListOfArticles = map.containsKey("listOfArticles");
  
        if (hasListOfArticles) {
            puts ("It has listOfArticles");
        } else {
            puts ("No listOfArticles!!!!. As we have not included listOfArticles, we are getting no list of articles");
        }
  
        // Parsed index but not an entire object
        GeekEmployee geekWithNoArticles = fromMap(map, GeekEmployee.class);
        puts ("geekWithNoArticles=", geekWithNoArticles);
  
        // Now manipulate the map too
        map = copy(map);
        map.put("listOfArticles", list("Mastering Java", "Mastering Collections", "Java Learning"));
        geekWithNoArticles = fromMap(map, GeekEmployee.class);
        puts ("geekWithArticles!=", geekWithNoArticles);
    }
}


On execution of the code, we can see the below output

geekA json data =  {"firstName":"GeekA","lastName":"GeekA","listOfArticles":["Java Programming!!","Python Programming"]} 
geekA object data =  GeekEmployee{firstName='GeekA', lastName='GeekA', listOfArticles=[Java Programming!!, Python Programming]} 
No listOfArticles!!!!. As we have not included listOfArticles, we are getting no list of articles 
geekWithNoArticles= GeekEmployee{firstName='GeekA', lastName='GeekA', listOfArticles=null} 
geekWithArticles!= GeekEmployee{firstName='GeekA', lastName='GeekA', listOfArticles=[Mastering Java, Mastering Collections, Java Learning]} 

Output:

 

Conclusion

Boon does not have a dependency. A single jar or a pom.xml entry is enough to work with it. An easier way of conversion from and to JSON can easily be achieved. It is the easiest way of parsing JSON.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads