Full featured JSON Parser, Data Model, and JSON Path integration
This project is maintained by xmljim
JEP API Guide » Getting Started
To parse JSON, you need obtain a JSONParser
instance from the JSONFactory
:
JSONFactory factory = JSONFactory.newFactory() //instantiate the JSONFactory
JSONParser parser = factory.newParser() //
JSONParser
MethodsThe JSONParser
interface includes several methods for loading a JSON instance:
parse(InputStream inputStream)
: parse from an InputStreamparse(InputStream inputStream, String charSet)
: parse from an InputStream using a specified Character Set (defaults to UTF-8)parse(URL url)
: parse from a URLparse(String data)
: parse a String JSON instanceparse(Reader reader)
: parse from a Readerparse(File file)
: parse from a Fileparse(Path path)
: parse from a Path instanceIn addition, you can also create an empty JSONObject
or JSONArray
instance:
newJSONObject()
newJSONArray()
Note: There is another way to create empty instances using,
NodeFactory.newJSONObject()
orNodeFactory.newJSONArray()
, both of which are syntactic sugar for creating aJSONFactory
, creating a newJSONParser
instance, and invoking the parser’snew*
method.
JSONFactory factory = JSONFactory.newFactory();
JSONParser parser = factory.newParser();
JSONNode json = null; //JSONNode is the superinterface for both JSONObject and JSONArray
try (InputStream stream = ...) {
json = parser.parse(stream);
} catch (IOException | JSONParserException e) {
//do something in the event of an error
}
//we've obtained a JSONNode instance. Now we can determine the type of Node and convert it:
if (json.isObject()) {
JSONObject jsonObject = json.asJSONObject();
//now we have access to all methods of the JSONObject
} else {
JSONArray jsonArray = json.asJSONArray();
//work with a JSONArray...
}
Sub-topics: