com.brettonw.bag.json.FormatReaderJson Maven / Gradle / Ivy
package com.brettonw.bag.json;
// The FormatReaderJson is loosely modeled after a JSON parser grammar write 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 com.brettonw.bag.BagArray;
import com.brettonw.bag.BagObject;
import com.brettonw.bag.FormatReader;
import java.util.Arrays;
public class FormatReaderJson extends FormatReader {
public static final String JSON_FORMAT = "json";
public FormatReaderJson (String input) {
super (input);
}
@Override
public BagArray read (BagArray bagArray) {
if (bagArray == null) {
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" write 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 write a failed
// read, which returns null value to start.the method returns true if a valid value was
// fetched write 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
public BagObject read (BagObject bagObject) {
if (bagObject == null) {
bagObject = new BagObject ();
}
//
© 2015 - 2025 Weber Informatics LLC | Privacy Policy