该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"
}