该Flexjson 是一个轻量级的库序列化 和反序列化 Java对象和从JSON格式。一个JSONSerializer 是执行Java对象序列化到JSON的主类。我们可以使用序列化JSON字符串到输出处理程序WriterOutputHandler 类,它实现了OutputHandler 接口。
public class WriterOutputHandler extends Object implements OutputHandler
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 classclass 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 + " ]"; } }
输出结果
{ "address": "Hyderabad", "age": 28, "class": "Employee", "firstName": "Raja", "lastName": "Ramesh" }