Json Simple 简明教程
JSON.simple - Customized Output
我们可以根据自定义类定制 JSON 输出。唯一的需求是实现 JSONAware 接口。
We can customize JSON output based on custom class. Only requirement is to implement JSONAware interface.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
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"));
System.out.println(students);
}
}
class Student implements JSONAware {
int rollNo;
String name;
Student(int rollNo, String name){
this.rollNo = rollNo;
this.name = name;
}
@Override
public String toJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("name");
sb.append(":");
sb.append("\"" + JSONObject.escape(name) + "\"");
sb.append(",");
sb.append("rollNo");
sb.append(":");
sb.append(rollNo);
sb.append("}");
return sb.toString();
}
}