如何在 Java 中将 JSON 字符串序列化为输出处理程序?
javajsonobject oriented programmingprogramming
Flexjson 是一个轻量级库,用于将 Java 对象序列化 和反序列化 为 JSON 格式。JSONSerializer 是执行 Java 对象到 JSON 序列化的主要类。我们可以使用 WriterOutputHandler 类将 JSON 字符串序列化为输出处理程序,它实现了 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" }