public class JSONParser extends Object implements JSONParseCallback
Fast and dirty parser for JSON content on the web, it essentially returns
a Map
object containing the object fields mapped to their values. If the value is
a nested object a nested Map
/List
is returned.
The JSONParser
returns a Map
which is great if the root object is a Map
but in
some cases its a list of elements (as is the case above). In this case a special case "root"
element is
created to contain the actual list of elements. See the sample below for exact usage of this.
The sample below includes JSON from https://anapioficeandfire.com/ generated by the query http://www.anapioficeandfire.com/api/characters?page=5&pageSize=3:
The sample code below fetches a page of data from the nestoria housing listing API as a list of Map elements.
You can see instructions on how to display the data in the InfiniteScrollAdapter
class.
Constructor and Description |
---|
JSONParser() |
Modifier and Type | Method and Description |
---|---|
void |
booleanToken(boolean tok)
Submits a boolean token from the JSON data
|
void |
endArray(String arrayName)
Indicates that the parser ran into an ending bracket event ]
|
void |
endBlock(String blockName)
Indicates that the parser ran into an ending bracket event }
|
boolean |
isAlive()
This method indicates to the Parser if this Callback is still alive
|
static boolean |
isIncludeNulls()
Deprecated.
Use
isIncludeNullsInstance() instead. |
boolean |
isIncludeNullsInstance()
Checks whether this parser will include null values in parsed content.
|
boolean |
isStrict()
Checks if this JSON parser is in strict mode.
|
static boolean |
isUseBoolean()
Deprecated.
Use
isUseBooleanInstance() instead. |
boolean |
isUseBooleanInstance()
Indicates that the parser will generate Boolean objects and not just Strings for boolean values
|
static boolean |
isUseLongs()
Deprecated.
Use
isUseLongsInstance() to check whether the current JSONParser uses longs. |
boolean |
isUseLongsInstance()
Checks to see if this parser generates long objects and not just doubles for numeric values.
|
void |
keyValue(String key,
String value)
This method is called when a string key/value pair is detected within the json
it is essentially redundant when following string/numeric token.
|
void |
longToken(long tok)
Submits a numeric token from the JSON data
|
static String |
mapToJson(Map<String,?> map)
Static method to convert the given
Map to a valid JSON
representation. |
void |
numericToken(double tok)
Submits a numeric token from the JSON data
|
Hashtable<String,Object> |
parse(Reader i)
Deprecated.
use the new parseJSON instead
|
static void |
parse(Reader i,
JSONParseCallback callback)
Static method! Parses the given input stream and fires the data into the given callback.
|
Map<String,Object> |
parseJSON(Reader i)
Parses the given input stream into this object and returns the parse tree.
The JSONParser returns a Map which is great if the root object is a Map but in
some cases its a list of elements (as is the case above). |
static void |
setIncludeNulls(boolean aIncludeNullsDefault)
Deprecated.
Use
setIncludeNullsInstance(boolean) instead. |
void |
setIncludeNullsInstance(boolean include)
Sets whether to include null values in parsed content.
|
void |
setStrict(boolean strict)
Enables or disables strict mode.
|
static void |
setUseBoolean(boolean aUseBooleanDefault)
Deprecated.
Use
setUseBooleanInstance(boolean) instead. |
void |
setUseBooleanInstance(boolean useBoolean)
Indicates that the parser will generate Boolean objects and not just Strings for boolean values
|
static void |
setUseLongs(boolean aUseLongsDefault)
Deprecated.
|
void |
setUseLongsInstance(boolean longs)
Sets the current JSONParser instance to use longs instead of doubles for numeric values.
|
void |
startArray(String arrayName)
Indicates that the parser ran into an opening bracket event [
|
void |
startBlock(String blockName)
Indicates that the parser ran into an opening bracket event {
|
void |
stringToken(String tok)
Submits a token from the JSON data as a java string, this token is always a string value
|
public static boolean isUseLongs()
isUseLongsInstance()
to check whether the current JSONParser uses longs.isUseLongsInstance()
to check the status for a particular
JSONParser object.public boolean isUseLongsInstance()
public static void setUseLongs(boolean aUseLongsDefault)
setUseLongsInstance(boolean)
Warning: This method will affect ALL JSONParser instances in the application. Prefer to use setUseLongsInstance(boolean)
to only affect the behaviour of the particular JSONParser instance.
aUseLongsDefault
- the useLongsDefault to setpublic void setUseLongsInstance(boolean longs)
setUseLongs(boolean)
so that it doesn't disrupt libraries that may depend on JSONParser.longs
- True to usepublic static boolean isIncludeNulls()
isIncludeNullsInstance()
instead.isIncludeNullsInstance()
.isIncludeNullsInstance()
.public static void setIncludeNulls(boolean aIncludeNullsDefault)
setIncludeNullsInstance(boolean)
instead.isIncludeNullsInstance()
.aIncludeNullsDefault
- the includeNullsDefault to setpublic void setIncludeNullsInstance(boolean include)
include
- True to include null values in parsed content.public boolean isIncludeNullsInstance()
public static boolean isUseBoolean()
isUseBooleanInstance()
instead.isUseBooleanInstance()
.public boolean isUseBooleanInstance()
public void setUseBooleanInstance(boolean useBoolean)
useBoolean
- True to generate Boolean objects and not just Strings for boolean values.public static void setUseBoolean(boolean aUseBooleanDefault)
setUseBooleanInstance(boolean)
instead.isUseBooleanInstance()
aUseBooleanDefault
- the useBooleanDefault to setpublic static void parse(Reader i, JSONParseCallback callback) throws IOException
i
- the readercallback
- a generic callback to receive the parse eventsIOException
- if thrown by the streampublic Map<String,Object> parseJSON(Reader i) throws IOException
Parses the given input stream into this object and returns the parse tree.
The JSONParser
returns a Map
which is great if the root object is a Map
but in
some cases its a list of elements (as is the case above). In this case a special case "root"
element is
created to contain the actual list of elements. See the sample below for exact usage of this.
The sample below includes JSON from https://anapioficeandfire.com/ generated by the query http://www.anapioficeandfire.com/api/characters?page=5&pageSize=3:
i
- the readerIOException
- if thrown by the streampublic Hashtable<String,Object> parse(Reader i) throws IOException
i
- the readerIOException
- if thrown by the streampublic void startBlock(String blockName)
startBlock
in interface JSONParseCallback
public void endBlock(String blockName)
endBlock
in interface JSONParseCallback
public boolean isStrict()
setStrict(boolean)
public void setStrict(boolean strict)
When strict mode is disabled, the parser will sanitize the JSON input before parsing. The effect is that it will be able to parse input that is json-ish.
'...'
Single quoted strings are converted to JSON strings.
\xAB
Hex escapes are converted to JSON unicode escapes.
\012
Octal escapes are converted to JSON unicode escapes.
0xAB
Hex integer literals are converted to JSON decimal
numbers.
012
Octal integer literals are converted to JSON decimal
numbers.
+.5
Decimal numbers are coerced to JSON's stricter format.
[0,,2]
Elisions in arrays are filled with null
.
[1,2,3,]
Trailing commas are removed.
{foo:"bar"}
Unquoted property names are quoted.
//comments
JS style line and block comments are removed.
(...)
Grouping parentheses are removed.
strict
- True to enable strict mode, false to disable it.isStrict()
public void startArray(String arrayName)
startArray
in interface JSONParseCallback
public void endArray(String arrayName)
endArray
in interface JSONParseCallback
public void stringToken(String tok)
stringToken
in interface JSONParseCallback
public void numericToken(double tok)
numericToken
in interface JSONParseCallback
tok
- the token valuepublic void longToken(long tok)
longToken
in interface JSONParseCallback
public void booleanToken(boolean tok)
booleanToken
in interface JSONParseCallback
tok
- the token valuepublic void keyValue(String key, String value)
keyValue
in interface JSONParseCallback
key
- the keyvalue
- a string valuepublic boolean isAlive()
isAlive
in interface JSONParseCallback
public static String mapToJson(Map<String,?> map)
Map
to a valid JSON
representation. The values allowed types are: Number
, String
, Boolean
,
List
, Map
or null.
Limited whitespace is inserted be make the resulting JSON string more
readable.
Simple example of usage:
Map<String, Object> person = new LinkedHashMap<>();
person.put("firstName", "Paco");
person.put("lastName", "Bellz");
person.put("isAlive", true);
person.put("age", 35);
person.put("weight (kg)", 70.7);
Log.p("--- mapToJson() test");
Log.p("\n" + mapToJson(person));
The output will be:
{
"firstName": "Paco",
"lastName": "Bellz",
"isAlive": true,
"age": 35,
"weight (kg)": 70.7
}
More complex example of usage:
Map<String, Object> phoneNumber1 = new LinkedHashMap<>();
phoneNumber1.put("home", "212 555-1234");
Map<String, Object> phoneNumber2 = new LinkedHashMap<>();
phoneNumber2.put("office", "646 555-4567");
Map<String, Object> phoneNumber3 = new LinkedHashMap<>();
phoneNumber3.put("mobile", "123 456-7890");
Map<String, Object> phoneNumber4 = new LinkedHashMap<>();
phoneNumber4.put("mobile", "06124578965");
ArrayList phoneNumbers = new ArrayList();
ArrayList phoneNumbers2 = new ArrayList();
phoneNumbers.add(phoneNumber1);
phoneNumbers.add(phoneNumber2);
phoneNumbers.add(phoneNumber3);
phoneNumbers2.add(phoneNumber4);
Map<String, Object> address1 = new LinkedHashMap<>();
address1.put("streetAddress", "53, London Street");
address1.put("city", "Paris");
address1.put("state", "FR");
address1.put("postalCode", "54856");
Map<String, Object> address2 = new LinkedHashMap<>();
address2.put("streetAddress", "21 2nd Street");
address2.put("city", "New York");
address2.put("state", "NY");
address2.put("postalCode", "10021-3100");
Map<String, Object> secondPerson = new LinkedHashMap<>();
secondPerson.put("firstName", "Gioia");
secondPerson.put("lastName", "Mia");
secondPerson.put("isAlive", true);
secondPerson.put("age", 34);
secondPerson.put("weight (kg)", 60.2);
secondPerson.put("address", address2);
address2.put("phoneNumbers", phoneNumbers2);
Map<String, Object> firstPerson = new LinkedHashMap<>();
firstPerson.put("firstName", "Paco");
firstPerson.put("lastName", "Bellz");
firstPerson.put("isAlive", true);
firstPerson.put("age", 35);
firstPerson.put("weight (kg)", 70.7);
firstPerson.put("address", address1);
firstPerson.put("partner", secondPerson);
firstPerson.put("children", new ArrayList());
firstPerson.put("extraInfo", null);
firstPerson.put("phoneNumbers", phoneNumbers);
List friends = new ArrayList();
friends.add("Paul");
friends.add("Karl");
friends.add("Mary");
firstPerson.put("onVacation", false);
firstPerson.put("friends", friends);
Log.p("--- mapToJson() test");
Log.p("\n" + mapToJson(firstPerson));
The output will be:
{
"firstName": "Paco",
"lastName": "Bellz",
"isAlive": true,
"age": 35,
"weight (kg)": 70.7,
"address": {
"streetAddress": "53, London Street",
"city": "Paris",
"state": "FR",
"postalCode": "54856"
},
"partner": {
"firstName": "Gioia",
"lastName": "Mia",
"isAlive": true,
"age": 34,
"weight (kg)": 60.2,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100",
"phoneNumbers": [{"mobile": "06124578965"}]
}
},
"children": [],
"extraInfo": null,
"phoneNumbers": [
{"home": "212 555-1234"},
{"office": "646 555-4567"},
{"mobile": "123 456-7890"}
],
"onVacation": false,
"friends": [
"Paul",
"Karl",
"Mary"
]
}
map
- The map to be converted to a JSON string