
com.brettonw.bag.JsonParser Maven / Gradle / Ivy
package com.brettonw.bag;
// The JsonParser is loosely modeled after a JSON parser grammar from the site (http://www.json.org).
// The main difference is that we ignore differences between value types (all of them will be
// strings internally), and assume the input is a well formed string representation of a BagObject
// or BagArray in JSON-ish format
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
class JsonParser extends Parser {
private static final Logger log = LogManager.getLogger (JsonParser.class);
JsonParser (String input) {
super (input);
}
JsonParser (InputStream inputStream) throws IOException {
super (inputStream);
}
JsonParser (File file) throws IOException {
super (file);
}
@Override
BagArray readBagArray () {
// :: [ ] | [ ]
BagArray bagArray = new BagArray();
return (expect('[') && readElements (bagArray) && require(']')) ? bagArray : null;
}
private boolean storeValue (BagArray bagArray) {
// the goal here is to try to read a "value" from the input stream, and store it into the
// BagArray. BagArrays can store null values, so we have a special handling case to make
// sure we properly convert "null" string to null value - as distinguished from a failed
// read, which returns null value to start.the method returns true if a valid value was
// fetched from the stream (in which case it was added to the BagArray)
Object value = readValue ();
if (value != null) {
// special case for "null"
if ((value instanceof String) && (((String) value).equalsIgnoreCase ("null"))) {
value = null;
}
bagArray.add (value);
return true;
}
return false;
}
private boolean readElements (BagArray bagArray) {
// ::= | ,
boolean result = true;
if (storeValue (bagArray)) {
while (expect (',')) {
result = require (storeValue (bagArray), "Valid value");
}
}
return result;
}
@Override
BagObject readBagObject () {
//
© 2015 - 2025 Weber Informatics LLC | Privacy Policy