如何在 Java 中将 JSON 字符串序列化到 Output Handler?
Flexjson 是一个轻量级库,用于将 Java 对象序列化和反序列化为 JSON 格式。JSONSerializer 是执行 Java 对象到 JSON 序列化的主要类。我们可以使用WriterOutputHandler 类将 JSON 字符串序列化到 Output Handler,它还实现了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 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 + " ]"; } }
输出
{ "address": "Hyderabad", "age": 28, "class": "Employee", "firstName": "Raja", "lastName": "Ramesh" }
广告