📅  最后修改于: 2020-11-16 07:17:38             🧑  作者: Mango
ContentHandler接口用于提供类似于SAX的接口以流式传输大型json。它还提供了可停止的功能。以下示例说明了该概念。
import java.io.IOException;
import java.util.List;
import java.util.Stack;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ContentHandler;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JsonDemo {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
String text = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
try {
CustomContentHandler handler = new CustomContentHandler();
parser.parse(text, handler,true);
} catch(ParseException pe) {
}
}
}
class CustomContentHandler implements ContentHandler {
@Override
public boolean endArray() throws ParseException, IOException {
System.out.println("inside endArray");
return true;
}
@Override
public void endJSON() throws ParseException, IOException {
System.out.println("inside endJSON");
}
@Override
public boolean endObject() throws ParseException, IOException {
System.out.println("inside endObject");
return true;
}
@Override
public boolean endObjectEntry() throws ParseException, IOException {
System.out.println("inside endObjectEntry");
return true;
}
public boolean primitive(Object value) throws ParseException, IOException {
System.out.println("inside primitive: " + value);
return true;
}
@Override
public boolean startArray() throws ParseException, IOException {
System.out.println("inside startArray");
return true;
}
@Override
public void startJSON() throws ParseException, IOException {
System.out.println("inside startJSON");
}
@Override
public boolean startObject() throws ParseException, IOException {
System.out.println("inside startObject");
return true;
}
@Override
public boolean startObjectEntry(String key) throws ParseException, IOException {
System.out.println("inside startObjectEntry: " + key);
return true;
}
}
inside startJSON
inside startObject
inside startObjectEntry: first
inside primitive: 123
inside endObjectEntry
inside startObjectEntry: second
inside startArray
inside primitive: 4
inside primitive: 5
inside primitive: 6
inside endArray
inside endObjectEntry
inside startObjectEntry: third
inside primitive: 789
inside endObjectEntry
inside endObject
inside endJSON