- JSON.simple 教程
- JSON.simple - 主页
- JSON.simple - 概述
- JSON.simple - 环境设置
- JSON.simple - JAVA 映射
- 解码示例
- 转义特殊字符
- JSON.simple - 使用 JSONValue
- JSON.simple - 异常处理
- JSON.simple - 容器工厂
- JSON.simple - 内容处理程序
- 编码示例
- JSON.simple - 编码 JSONObject
- JSON.simple - 编码 JSONArray
- 合并示例
- JSON.simple - 合并对象
- JSON.simple - 合并数组
- 组合示例
- JSON.simple - 原始、对象、数组
- JSON.simple - 原始、映射、列表
- 基元、对象、映射、列表
- 定制示例
- JSON.simple - 自定义输出
- 定制输出流
- JSON.simple 有用资源
- JSON.simple - 快速指南
- JSON.simple - 有用的资源
- JSON.simple - 讨论
JSON.simple - 定制输出流
我们可以根据自定义类自定义 JSON 流输出。唯一的要求是实现 JSONStreamAware 接口。
下面的例子说明了上述概念。
例子
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONArray students = new JSONArray();
students.add(new Student(1,"Robert"));
students.add(new Student(2,"Julia"));
StringWriter out = new StringWriter();
students.writeJSONString(out);
System.out.println(out.toString());
}
}
class Student implements JSONStreamAware {
int rollNo;
String name;
Student(int rollNo, String name){
this.rollNo = rollNo;
this.name = name;
}
@Override
public void writeJSONString(Writer out) throws IOException {
Map obj = new LinkedHashMap();
obj.put("name", name);
obj.put("rollNo", new Integer(rollNo));
JSONValue.writeJSONString(obj, out);
}
}
输出
[{name:"Robert",rollNo:1},{name:"Julia",rollNo:2}]