mjson
public class Json extends java.lang.Object
Represents a JSON (JavaScript Object Notation) entity. For more information about JSON, please see http://www.json.org.
A JSON entity can be one of several things: an object (set of name/Json entity pairs), an array (a list of
other JSON entities), a string, a number, a boolean or null. All of those are represented as Json
instances. Each of the different types of entities supports a different set of operations. However, this class
unifies all operations into a single interface so in Java one is always dealing with a single object type: this class.
The approach effectively amounts to dynamic typing where using an unsupported operation won't be detected at
compile time, but will throw a runtime UnsupportedOperationException
. It simplifies working with JSON
structures considerably and it leads to shorter at cleaner Java code. It makes much easier to work
with JSON structure without the need to convert to "proper" Java representation in the form of
POJOs and the like. When traversing a JSON, there's no need to type-cast at each step because there's
only one type: Json
.
One can examine the concrete type of a Json
with one of the isXXX
methods:
isObject()
, isArray()
,isNumber()
,isBoolean()
,isString()
,
isNull()
.
The underlying representation of a given Json
instance can be obtained by calling
the generic getValue()
method or one of the asXXX
methods such
as asBoolean()
or asString()
etc.
JSON objects are represented as Java Map
s while JSON arrays are represented as Java
List
s. Because those are mutable aggregate structures, there are two versions of the
corresponding asXXX
methods: asMap()
which performs a deep copy of the underlying
map, unwrapping every nested Json entity to its Java representation and asJsonMap()
which
simply return the map reference. Similarly there are asList()
and asJsonList()
.
There are several static factory methods in this class that allow you to create new
Json
instances:
read(String) |
Parse a JSON string and return the resulting Json instance. The syntax
recognized is as defined in http://www.json.org.
|
make(Object) |
Creates a Json instance based on the concrete type of the parameter. The types
recognized are null, numbers, primitives, String, Map, Collection, Java arrays
and Json itself. |
nil() |
Return a Json instance representing JSON null . |
object() |
Create and return an empty JSON object. |
object(Object...) |
Create and return a JSON object populated with the key/value pairs
passed as an argument sequence. Each even parameter becomes a key (via
toString ) and each odd parameter is converted to a Json
value. |
array() |
Create and return an empty JSON array. |
array(Object...) |
Create and return a JSON array from the list of arguments. |
To customize how Json elements are represented and to provide your own version of the
make(Object)
method, you create an implementation of the Json.Factory
interface
and configure it either globally with the setGlobalFactory(Factory)
method or
on a per-thread basis with the attachFactory(Factory)
/dettachFactory()
methods.
If a Json
instance is an object, you can set its properties by
calling the set(String, Object)
method which will add a new property or replace an existing one.
Adding elements to an array Json
is done with the add(Object)
method.
Removing elements by their index (or key) is done with the delAt(int)
(or
delAt(String)
) method. You can also remove an element from an array without
knowing its index with the remove(Object)
method. All these methods return the
Json
instance being manipulated so that method calls can be chained.
If you want to remove an element from an object or array and return the removed element
as a result of the operation, call atDel(int)
or atDel(String)
instead.
If you want to add properties to an object in bulk or append a sequence of elements to array,
use the with(Json)
method. When used on an object, this method expects another
object as its argument and it will copy all properties of that argument into itself. Similarly,
when called on array, the method expects another array and it will append all elements of its
argument to itself.
To make a clone of a Json object, use the dup()
method. This method will create a new
object even for the immutable primitive Json types. Objects and arrays are cloned
(i.e. duplicated) recursively.
The at(int)
method returns the array element at the specified index and the
at(String)
method does the same for a property of an object instance. You can
use the at(String, Object)
version to create an object property with a default
value if it doesn't exist already.
To test just whether a Json object has a given property, use the has(String)
method. To test
whether a given object property or an array elements is equal to a particular value, use the
is(String, Object)
and is(int, Object)
methods respectively. Those methods return
true if the given named property (or indexed element) is equal to the passed in Object as the second
parameter. They return false if an object doesn't have the specified property or an index array is out
of bounds. For example is(name, value) is equivalent to 'has(name) && at(name).equals(make(value))'.
To help in navigating JSON structures, instances of this class contain a reference to the
enclosing JSON entity (object or array) if any. The enclosing entity can be accessed
with up()
method.
The combination of method chaining when modifying Json
instances and
the ability to navigate "inside" a structure and then go back to the enclosing
element lets one accomplish a lot in a single Java statement, without the need
of intermediary variables. Here for example how the following JSON structure can
be created in one statement using chained calls:
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
"position": 0
}}
import mjson.Json;
import static mjson.Json.*;
...
Json j = object()
.at("menu", object())
.set("id", "file")
.set("value", "File")
.at("popup", object())
.at("menuitem", array())
.add(object("value", "New", "onclick", "CreateNewDoc()"))
.add(object("value", "Open", "onclick", "OpenDoc()"))
.add(object("value", "Close", "onclick", "CloseDoc()"))
.up()
.up()
.set("position", 0)
.up();
...
If there's no danger of naming conflicts, a static import of the factory methods (
import static json.Json.*;
) would reduce typing even further and make the code more
readable.
To get a compact string representation, simply use the Object.toString()
method. If you
want to wrap it in a JavaScript callback (for JSON with padding), use the pad(String)
method.
Since version 1.3, mJson supports JSON Schema, draft 4. A schema is represented by the internal
class Json.Schema
. To perform a validation, you have a instantiate a Json.Schema
using the factory method mjson.Json.schema
and then call its validate
method
on a JSON instance:
import mjson.Json;
import static mjson.Json.*;
...
Json inputJson = Json.read(inputString);
Json schema = Json.schema(new URI("http://mycompany.com/schemas/model"));
Json errors = schema.validate(inputJson);
for (Json error : errors.asJsonList())
System.out.println("Validation error " + err);
Modifier and Type | Class and Description |
---|---|
static class |
Json.DefaultFactory |
static interface |
Json.Factory
This interface defines how
Json instances are constructed. |
static interface |
Json.Schema
Represents JSON schema - a specific data format that a JSON entity must
follow.
|
Modifier and Type | Field and Description |
---|---|
static Json.Factory |
defaultFactory |
Modifier | Constructor and Description |
---|---|
protected |
Json() |
protected |
Json(Json enclosing) |
Modifier and Type | Method and Description |
---|---|
Json |
add(Json el)
Add the specified
Json element to this array. |
Json |
add(java.lang.Object anything)
Add an arbitrary Java object to this
Json array. |
static Json |
array()
Return a new constructed, empty JSON array.
|
static Json |
array(java.lang.Object... args)
Return a new JSON array filled up with the list of arguments.
|
boolean |
asBoolean()
Return the boolean value of a boolean
Json instance. |
byte |
asByte()
Return the byte value of a number
Json instance. |
char |
asChar()
Return the first character of a string
Json instance. |
double |
asDouble()
Return the double value of a number
Json instance. |
float |
asFloat()
Return the float value of a float
Json instance. |
int |
asInteger()
Return the integer value of a number
Json instance. |
java.util.List<Json> |
asJsonList()
Return the underlying
List representation of a Json array. |
java.util.Map<java.lang.String,Json> |
asJsonMap()
Return the underlying map of properties of a
Json object. |
java.util.List<java.lang.Object> |
asList()
Return a list of the elements of a
Json array. |
long |
asLong()
Return the long value of a number
Json instance. |
java.util.Map<java.lang.String,java.lang.Object> |
asMap()
Return a map of the properties of an object
Json instance. |
short |
asShort()
Return the short value of a number
Json instance. |
java.lang.String |
asString()
Return the string value of a string
Json instance. |
Json |
at(int index)
Return the
Json element at the specified index of this
Json array. |
Json |
at(java.lang.String property)
Return the specified property of a
Json object or null
if there's no such property. |
Json |
at(java.lang.String property,
Json def)
Return the specified property of a
Json object if it exists. |
Json |
at(java.lang.String property,
java.lang.Object def)
Return the specified property of a
Json object if it exists. |
Json |
atDel(int index)
Remove the element at the specified index from a
Json array and return
that element. |
Json |
atDel(java.lang.String property)
Remove the specified property from a
Json object and return
that property. |
static void |
attachFactory(Json.Factory factory)
Attach a thread-local Json
Json.Factory to be used specifically by this thread. |
void |
attachTo(Json enclosing)
Explicitly set the parent of this element.
|
Json |
delAt(int index)
Remove the element at the specified index from a
Json array. |
Json |
delAt(java.lang.String property)
Delete the specified property from a
Json object. |
static void |
dettachFactory()
Clear the thread-local factory previously attached to this thread via the
attachFactory(Factory) method. |
Json |
dup()
Return a clone (a duplicate) of this
Json entity. |
java.lang.Object |
getValue()
Return the underlying value of this
Json entity. |
boolean |
has(java.lang.String property)
Return true if this
Json object has the specified property
and false otherwise. |
boolean |
is(int index,
java.lang.Object value)
Return
true if and only if this Json array has an element with
the specified value at the specified index. |
boolean |
is(java.lang.String property,
java.lang.Object value)
Return
true if and only if this Json object has a property with
the specified value. |
boolean |
isArray()
Return
true if this is a Json array (i.e. |
boolean |
isBoolean()
Return
true if this is a Json boolean entity
and false otherwise. |
boolean |
isNull()
Return
true if this is a Json null entity
and false otherwise. |
boolean |
isNumber()
Return
true if this is a Json number entity
and false otherwise. |
boolean |
isObject()
Return
true if this is a Json object entity
and false otherwise. |
boolean |
isPrimitive()
Return
true if this is a Json primitive entity
(one of string, number or boolean) and false otherwise. |
boolean |
isString()
Return
true if this is a Json string entity
and false otherwise. |
static Json |
make(java.lang.Object anything)
Convert an arbitrary Java instance to a
Json instance. |
static Json |
nil()
Return the
null Json instance. |
static Json |
object()
Return a newly constructed, empty JSON object.
|
static Json |
object(java.lang.Object... args)
Return a new JSON object initialized from the passed list of
name/value pairs.
|
java.lang.String |
pad(java.lang.String callback)
Json-pad this object as an argument to a callback function.
|
static Json |
read(java.text.CharacterIterator it)
Parse a JSON entity from a
CharacterIterator . |
static Json |
read(java.lang.String jsonAsString)
Parse a JSON entity from its string representation.
|
static Json |
read(java.net.URL location)
Parse a JSON entity from a
URL . |
Json |
remove(Json el)
Remove the specified element from a
Json array. |
Json |
remove(java.lang.Object anything)
Remove the specified Java object (converted to a Json instance)
from a
Json array. |
static Json.Schema |
schema(Json S) |
static Json.Schema |
schema(Json S,
java.net.URI uri) |
static Json.Schema |
schema(java.net.URI uri) |
Json |
set(int index,
java.lang.Object value)
Change the value of a JSON array element.
|
Json |
set(java.lang.String property,
Json value)
Set a
Json objects's property. |
Json |
set(java.lang.String property,
java.lang.Object value)
Set a
Json objects's property. |
static void |
setGlobalFactory(Json.Factory factory)
Specify a global Json
Json.Factory to be used by all threads that don't have a
specific thread-local factory attached to them. |
java.lang.String |
toString(int maxCharacters)
Return a string representation of
this that does
not exceed a certain maximum length. |
Json |
up()
Return the
Json entity, if any, enclosing this
Json . |
Json |
with(Json object)
Combine this object or array with the passed in object or array.
|
public static final Json.Factory defaultFactory
protected Json()
protected Json(Json enclosing)
public static Json.Schema schema(Json S)
public static Json.Schema schema(java.net.URI uri)
public static Json.Schema schema(Json S, java.net.URI uri)
public static void setGlobalFactory(Json.Factory factory)
Specify a global Json Json.Factory
to be used by all threads that don't have a
specific thread-local factory attached to them.
factory
- public static void attachFactory(Json.Factory factory)
Attach a thread-local Json Json.Factory
to be used specifically by this thread. Thread-local
Json factories are the only means to have different Json.Factory
implementations used simultaneously
in the same application (well, more accurately, the same ClassLoader).
factory
- public static void dettachFactory()
Clear the thread-local factory previously attached to this thread via the
attachFactory(Factory)
method. The global factory takes effect after
a call to this method.
public static Json read(java.lang.String jsonAsString)
Parse a JSON entity from its string representation.
jsonAsString
- A valid JSON representation as per the json.org
grammar. Cannot be null
.null
.public static Json read(java.net.URL location)
Parse a JSON entity from a URL
.
location
- A valid URL where to load a JSON document from. Cannot be null
.null
.public static Json read(java.text.CharacterIterator it)
Parse a JSON entity from a CharacterIterator
.
read(String)
public static Json nil()
Return the null Json
instance.
public static Json object()
Return a newly constructed, empty JSON object.
public static Json object(java.lang.Object... args)
Return a new JSON object initialized from the passed list of
name/value pairs. The number of arguments must
be even. Each argument at an even position is taken to be a name
for the following value. The name arguments are normally of type
Java String, but they can be of any other type having an appropriate
toString
method. Each value is first converted
to a Json
instance using the make(Object)
method.
args
- A sequence of name value pairs.public static Json array()
Return a new constructed, empty JSON array.
public static Json array(java.lang.Object... args)
Return a new JSON array filled up with the list of arguments.
args
- The initial content of the array.public static Json make(java.lang.Object anything)
Convert an arbitrary Java instance to a Json
instance.
Maps, Collections and arrays are recursively copied where each of
their elements concerted into Json
instances as well. The keys
of a Map
parameter are normally strings, but anything with a meaningful
toString
implementation will work as well.
anything
- Json
. This method will never return null
. It will
throw an IllegalArgumentException
if it doesn't know how to convert the argument
to a Json
instance.java.lang.IllegalArgumentException
- when the concrete type of the parameter is
unknown.public java.lang.String toString(int maxCharacters)
Return a string representation of this
that does
not exceed a certain maximum length. This is useful in constructing
error messages or any other place where only a "preview" of the
JSON element should be displayed. Some JSON structures can get
very large and this method will help avoid string serializing
the whole of them.
maxCharacters
- The maximum number of characters for
the string representation.public void attachTo(Json enclosing)
Explicitly set the parent of this element. The parent is presumably an array
or an object. Normally, there's no need to call this method as the parent is
automatically set by the framework. You may need to call it however, if you implement
your own Json.Factory
with your own implementations of the Json types.
enclosing
- The parent element.public final Json up()
Return the Json
entity, if any, enclosing this
Json
. The returned value can be null
or
a Json
object or list, but not one of the primitive types.
public Json dup()
Return a clone (a duplicate) of this Json
entity. Note that cloning
is deep if array and objects. Primitives are also cloned, even though their values are immutable
because the new enclosing entity (the result of the up()
method) may be different.
since they are immutable.
public Json at(int index)
Return the Json
element at the specified index of this
Json
array. This method applies only to Json arrays.
index
- The index of the desired element.public Json at(java.lang.String property)
Return the specified property of a Json
object or null
if there's no such property. This method applies only to Json objects.
public final Json at(java.lang.String property, Json def)
Return the specified property of a Json
object if it exists.
If it doesn't, then create a new property with value the def
parameter and return that parameter.
property
- The property to return.def
- The default value to set and return in case the property doesn't exist.public final Json at(java.lang.String property, java.lang.Object def)
Return the specified property of a Json
object if it exists.
If it doesn't, then create a new property with value the def
parameter and return that parameter.
property
- The property to return.def
- The default value to set and return in case the property doesn't exist.public boolean has(java.lang.String property)
Return true if this Json
object has the specified property
and false otherwise.
property
- The name of the property.public boolean is(java.lang.String property, java.lang.Object value)
Return true
if and only if this Json
object has a property with
the specified value. In particular, if the object has no such property false
is returned.
property
- The property name.value
- The value to compare with. Comparison is done via the equals method.
If the value is not an instance of Json
, it is first converted to
such an instance.public boolean is(int index, java.lang.Object value)
Return true
if and only if this Json
array has an element with
the specified value at the specified index. In particular, if the array has no element at
this index, false
is returned.
property
- The property name.value
- The value to compare with. Comparison is done via the equals method.
If the value is not an instance of Json
, it is first converted to
such an instance.public final Json add(java.lang.Object anything)
Add an arbitrary Java object to this Json
array. The object
is first converted to a Json
instance by calling the static
make(java.lang.Object)
method.
anything
- Any Java object that can be converted to a Json instance.public Json atDel(java.lang.String property)
Remove the specified property from a Json
object and return
that property.
property
- The property to be removed.null
if the object didn't have such
a property to begin with.public Json atDel(int index)
Remove the element at the specified index from a Json
array and return
that element.
index
- The index of the element to delete.public Json delAt(java.lang.String property)
Delete the specified property from a Json
object.
property
- The property to be removed.public Json delAt(int index)
Remove the element at the specified index from a Json
array.
index
- The index of the element to delete.public Json remove(Json el)
Remove the specified element from a Json
array.
el
- The element to delete.public final Json remove(java.lang.Object anything)
Remove the specified Java object (converted to a Json instance)
from a Json
array. This is equivalent to
remove(
.
#make(anything)
)
anything
- The object to delete.public Json set(java.lang.String property, Json value)
Set a Json
objects's property.
property
- The property name.value
- The value of the property.public final Json set(java.lang.String property, java.lang.Object value)
Set a Json
objects's property.
property
- The property name.value
- The value of the property, converted to a Json
representation
with make(java.lang.Object)
.public Json set(int index, java.lang.Object value)
Change the value of a JSON array element. This must be an array.
index
- 0-based index of the element in the array.value
- the new value of the elementpublic Json with(Json object)
Combine this object or array with the passed in object or array. The types of
this
and the object
argument must match. If both are
Json
objects, all properties of the parameter are added to this
.
If both are arrays, all elements of the parameter are appended to this
object
- The object or array whose properties or elements must be added to this
Json object or array.public java.lang.Object getValue()
Return the underlying value of this Json
entity. The actual value will
be a Java Boolean, String, Number, Map, List or null. For complex entities (objects
or arrays), the method will perform a deep copy and extra underlying values recursively
for all nested elements.
public boolean asBoolean()
Return the boolean value of a boolean Json
instance. Call
isBoolean()
first if you're not sure this instance is indeed a
boolean.
public java.lang.String asString()
Return the string value of a string Json
instance. Call
isString()
first if you're not sure this instance is indeed a
string.
public int asInteger()
Return the integer value of a number Json
instance. Call
isNumber()
first if you're not sure this instance is indeed a
number.
public float asFloat()
Return the float value of a float Json
instance. Call
isNumber()
first if you're not sure this instance is indeed a
number.
public double asDouble()
Return the double value of a number Json
instance. Call
isNumber()
first if you're not sure this instance is indeed a
number.
public long asLong()
Return the long value of a number Json
instance. Call
isNumber()
first if you're not sure this instance is indeed a
number.
public short asShort()
Return the short value of a number Json
instance. Call
isNumber()
first if you're not sure this instance is indeed a
number.
public byte asByte()
Return the byte value of a number Json
instance. Call
isNumber()
first if you're not sure this instance is indeed a
number.
public char asChar()
Return the first character of a string Json
instance. Call
isString()
first if you're not sure this instance is indeed a
string.
public java.util.Map<java.lang.String,java.lang.Object> asMap()
Return a map of the properties of an object Json
instance. The map
is a clone of the object and can be modified safely without affecting it. Call
isObject()
first if you're not sure this instance is indeed a
Json
object.
public java.util.Map<java.lang.String,Json> asJsonMap()
Return the underlying map of properties of a Json
object. The returned
map is the actual object representation so any modifications to it are modifications
of the Json
object itself. Call
isObject()
first if you're not sure this instance is indeed a
Json
object.
public java.util.List<java.lang.Object> asList()
Return a list of the elements of a Json
array. The list is a clone
of the array and can be modified safely without affecting it. Call
isArray()
first if you're not sure this instance is indeed a
Json
array.
public java.util.List<Json> asJsonList()
Return the underlying List
representation of a Json
array.
The returned list is the actual array representation so any modifications to it
are modifications of the Json
array itself. Call
isArray()
first if you're not sure this instance is indeed a
Json
array.
public boolean isNull()
Return true
if this is a Json
null entity
and false
otherwise.
public boolean isString()
Return true
if this is a Json
string entity
and false
otherwise.
public boolean isNumber()
Return true
if this is a Json
number entity
and false
otherwise.
public boolean isBoolean()
Return true
if this is a Json
boolean entity
and false
otherwise.
public boolean isArray()
Return true
if this is a Json
array (i.e. list) entity
and false
otherwise.
public boolean isObject()
Return true
if this is a Json
object entity
and false
otherwise.
public boolean isPrimitive()
Return true
if this is a Json
primitive entity
(one of string, number or boolean) and false
otherwise.
public java.lang.String pad(java.lang.String callback)
Json-pad this object as an argument to a callback function.
callback
- The name of the callback function. Can be null or empty,
in which case no padding is done.callback
is not null or empty, or just the stringified version of the object.Copyright © 2014. All Rights Reserved.