How to serialize a JSON string to an Output Handler in Java?

JavaJSONObject Oriented ProgrammingProgramming

The Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON format. A JSONSerializer is the main class for performing serialization of Java objects to JSON. We can serialize a JSON string to an Output Handler using the WriterOutputHandler class and it implements the OutputHandler interface.

Syntax

public class WriterOutputHandler extends Object implements OutputHandler

Example

import java.io.*;
import flexjson.JSONSerializer;
import flexjson.OutputHandler;
import flexjson.WriterOutputHandler;
public class JsonOutputHandlerTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().prettyPrint(true); // pretty print JSON
      Employee emp = new Employee("Raja", "Ramesh", 28, "Hyderabad");
      OutputHandler out = new WriterOutputHandler(new StringWriter());
      serializer.serialize(emp, out);
      System.out.println(out.toString());
   }
}
// Employee class
class Employee {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Employee() {
   }
   public Employee(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public String getAddress() {
      return address;
   }
   public String toString() {
      return "Employee[ " +
             "firstName = " + firstName +
             ", lastName = " + lastName +
             ", age = " + age +
             ", address = " + address +
             " ]";
   }
}

Output

{
 "address": "Hyderabad",
 "age": 28,
 "class": "Employee",
 "firstName": "Raja",
 "lastName": "Ramesh"
}
raja
Published on 16-Oct-2019 11:11:29
Advertisements