Class Json
- All Implemented Interfaces:
Serializable
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()
.
Constructing and Modifying JSON Structures
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)
/detachFactory()
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, Json...opts)
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.
Navigating JSON Structures
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.
Converting to String
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.
Validating with JSON Schema
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 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);
Infinispan changes on top of 1.4.2:
- Added support for pretty printing
toPrettyString()
- Added support for
Json.RawJson
as a specializedJson.StringJson
- Usage of
LinkedHashMap
internally forJson.ObjectJson
for predictable iteration - Support for
Class
,Properties
,Enum
forJson.DefaultFactory.make(Object)
- Support from internal Infinispan classes for
Json.DefaultFactory.make(Object)
:MediaType
,JsonSerialization
,invalid reference
ConfigurationInfo
- Support for replacing objects
- Version:
- 1.4.2
- Author:
- Borislav Iordanov
- See Also:
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
static interface
This interface defines howJson
instances are constructed.static interface
static class
Exposes some internal methods that are useful forJson.Factory
implementations or other extension/layers of the library.static class
static interface
Represents JSON schema - a specific data format that a JSON entity must follow. -
Field Summary
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionfinal Json
Add an arbitrary Java object to thisJson
array.Add the specifiedJson
element to this array.static Json
array()
static Json
Return a new JSON array filled up with the list of arguments.boolean
byte
asByte()
char
asChar()
double
asDouble()
float
asFloat()
int
asList()
long
asLong()
asMap()
short
asShort()
asString()
at
(int index) Return theJson
element at the specified index of thisJson
array.Return the specified property of aJson
object ornull
if there's no such property.final Json
Return the specified property of aJson
object if it exists.final Json
Return the specified property of aJson
object if it exists.atDel
(int index) Remove the element at the specified index from aJson
array and return that element.Remove the specified property from aJson
object and return that property.static void
attachFactory
(Json.Factory factory) Attach a thread-local JsonJson.Factory
to be used specifically by this thread.void
Explicitly set the parent of this element.protected Json
collectWithOptions
(Json... options) Return an object representing the complete configuration of a merge.delAt
(int index) Remove the element at the specified index from aJson
array.Delete the specified property from aJson
object.static void
Clear the thread-local factory previously attached to this thread via theattachFactory(Factory)
method.dup()
static void
escape
(CharSequence sequence, Appendable out) static Json.Factory
factory()
Return theJson.Factory
currently in effect.int
int
getLine()
getValue()
boolean
Return true if thisJson
object has the specified property and false otherwise.boolean
Returntrue
if and only if thisJson
array has an element with the specified value at the specified index.boolean
Returntrue
if and only if thisJson
object has a property with the specified value.boolean
isArray()
boolean
boolean
isNull()
boolean
isNumber()
boolean
isObject()
boolean
boolean
isRaw()
boolean
isString()
location
(int line, int column) static void
static Json
Convert an arbitrary Java instance to aJson
instance.static Json
nil()
static Json
object()
static Json
Return a new JSON object initialized from the passed list of name/value pairs.Json-pad this object as an argument to a callback function.static Json
Parse a JSON entity from its string representation.static Json
Parse a JSON entity from aURL
.static Json
Parse a JSON entity from aCharacterIterator
.final Json
Remove the specified Java object (converted to a Json instance) from aJson
array.Remove the specified element from aJson
array.static Json.Schema
static Json.Schema
schema
(URI uri, Json.Function<URI, Json> relativeReferenceResolver) static Json.Schema
static Json.Schema
Change the value of a JSON array element.final Json
Set aJson
objects's property.Set aJson
objects's property.static void
setGlobalFactory
(Json.Factory factory) Specify a global JsonJson.Factory
to be used by all threads that don't have a specific thread-local factory attached to them.toString
(int maxCharacters) Return a string representation ofthis
that does not exceed a certain maximum length.final Json
up()
Same as{}@link #with(Json,Json...options)}
with each option argument converted toJson
first.Combine this object or array with the passed in object or array.
-
Field Details
-
defaultFactory
-
-
Constructor Details
-
Json
protected Json() -
Json
-
-
Method Details
-
schema
-
schema
-
schema
-
schema
-
factory
Return the
Json.Factory
currently in effect. This is the factory that themake(Object)
method will dispatch on upon determining the type of its argument. If you already know the type of element to construct, you can avoid the type introspection implicit to the make method and call the factory directly. This will result in an optimization.- Returns:
- the factory
-
escape
- Throws:
IOException
-
setGlobalFactory
Specify a global Json
Json.Factory
to be used by all threads that don't have a specific thread-local factory attached to them.- Parameters:
factory
- The new global factory
-
attachFactory
Attach a thread-local Json
Json.Factory
to be used specifically by this thread. Thread-local Json factories are the only means to have differentJson.Factory
implementations used simultaneously in the same application (well, more accurately, the same ClassLoader).- Parameters:
factory
- the new thread local factory
-
detachFactory
public static void detachFactory()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. -
read
Parse a JSON entity from its string representation.
- Parameters:
jsonAsString
- A valid JSON representation as per the json.org grammar. Cannot benull
.- Returns:
- The JSON entity parsed: an object, array, string, number or boolean, or null. Note that this method will
never return the actual Java
null
.
-
read
Parse a JSON entity from a
URL
.- Parameters:
location
- A valid URL where to load a JSON document from. Cannot benull
.- Returns:
- The JSON entity parsed: an object, array, string, number or boolean, or null. Note that this method will
never return the actual Java
null
.
-
read
Parse a JSON entity from a
CharacterIterator
.- Parameters:
it
- A character iterator.- Returns:
- the parsed JSON element
- See Also:
-
nil
- Returns:
- the
null Json
instance.
-
object
- Returns:
- a newly constructed, empty JSON object.
-
object
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 aJson
instance using themake(Object)
method.- Parameters:
args
- A sequence of name value pairs.- Returns:
- the new JSON object.
-
array
- Returns:
- a new constructed, empty JSON array.
-
array
Return a new JSON array filled up with the list of arguments.
- Parameters:
args
- The initial content of the array.- Returns:
- the new JSON array
-
make
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 aMap
parameter are normally strings, but anything with a meaningfultoString
implementation will work as well.- Parameters:
anything
- Any Java object that the current JSON factory in effect is capable of handling.- Returns:
- The
Json
. This method will never returnnull
. It will throw anIllegalArgumentException
if it doesn't know how to convert the argument to aJson
instance. - Throws:
IllegalArgumentException
- when the concrete type of the parameter is unknown.
-
location
-
getLine
public int getLine() -
getColumn
public int getColumn() -
toString
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.- Parameters:
maxCharacters
- The maximum number of characters for the string representation.- Returns:
- The string representation of this object.
-
toPrettyString
-
attachTo
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.- Parameters:
enclosing
- The parent element.
-
up
- Returns:
- the
Json
entity, if any, enclosing thisJson
. The returned value can benull
or aJson
object or list, but not one of the primitive types.
-
dup
- Returns:
- 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 theup()
method) may be different. since they are immutable.
-
at
Return the
Json
element at the specified index of thisJson
array. This method applies only to Json arrays.- Parameters:
index
- The index of the desired element.- Returns:
- The JSON element at the specified index in this array.
-
at
Return the specified property of a
Json
object ornull
if there's no such property. This method applies only to Json objects.- Parameters:
property
- the property name.- Returns:
- The JSON element that is the value of that property.
-
at
Return the specified property of a
Json
object if it exists. If it doesn't, then create a new property with value thedef
parameter and return that parameter.- Parameters:
property
- The property to return.def
- The default value to set and return in case the property doesn't exist.
-
at
Return the specified property of a
Json
object if it exists. If it doesn't, then create a new property with value thedef
parameter and return that parameter.- Parameters:
property
- The property to return.def
- The default value to set and return in case the property doesn't exist.
-
has
Return true if this
Json
object has the specified property and false otherwise.- Parameters:
property
- The name of the property.
-
is
Return
true
if and only if thisJson
object has a property with the specified value. In particular, if the object has no such propertyfalse
is returned.- Parameters:
property
- The property name.value
- The value to compare with. Comparison is done via the equals method. If the value is not an instance ofJson
, it is first converted to such an instance.- Returns:
-
is
Return
true
if and only if thisJson
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.- Parameters:
index
- The 0-based index of the element in a JSON array.value
- The value to compare with. Comparison is done via the equals method. If the value is not an instance ofJson
, it is first converted to such an instance.- Returns:
-
add
Add the specified
Json
element to this array.- Returns:
- this
-
add
Add an arbitrary Java object to this
Json
array. The object is first converted to aJson
instance by calling the staticmake(java.lang.Object)
method.- Parameters:
anything
- Any Java object that can be converted to a Json instance.- Returns:
- this
-
atDel
Remove the specified property from a
Json
object and return that property.- Parameters:
property
- The property to be removed.- Returns:
- The property value or
null
if the object didn't have such a property to begin with.
-
atDel
Remove the element at the specified index from a
Json
array and return that element.- Parameters:
index
- The index of the element to delete.- Returns:
- The element value.
-
delAt
Delete the specified property from a
Json
object.- Parameters:
property
- The property to be removed.- Returns:
- this
-
delAt
Remove the element at the specified index from a
Json
array.- Parameters:
index
- The index of the element to delete.- Returns:
- this
-
remove
Remove the specified element from a
Json
array.- Parameters:
el
- The element to delete.- Returns:
- this
-
remove
Remove the specified Java object (converted to a Json instance) from a
Json
array. This is equivalent toremove(
.make(Object)
)- Parameters:
anything
- The object to delete.- Returns:
- this
-
set
Set a
Json
objects's property.- Parameters:
property
- The property name.value
- The value of the property.- Returns:
- this
-
set
Set a
Json
objects's property.- Parameters:
property
- The property name.value
- The value of the property, converted to aJson
representation withmake(java.lang.Object)
.- Returns:
- this
-
set
Change the value of a JSON array element. This must be an array.
- Parameters:
index
- 0-based index of the element in the array.value
- the new value of the element- Returns:
- this
-
with
Combine this object or array with the passed in object or array. The types of
this
and theobject
argument must match. If both areJson
objects, all properties of the parameter are added tothis
. If both are arrays, all elements of the parameter are appended tothis
- Parameters:
object
- The object or array whose properties or elements must be added to this Json object or array.options
- A sequence of options that governs the merging process.- Returns:
- this
-
with
Same as{}@link #with(Json,Json...options)}
with each option argument converted toJson
first. -
replace
-
getValue
- Returns:
- 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.
-
asBoolean
public boolean asBoolean()- Returns:
- the boolean value of a boolean
Json
instance. CallisBoolean()
first if you're not sure this instance is indeed a boolean.
-
asString
- Returns:
- the string value of a string
Json
instance. CallisString()
first if you're not sure this instance is indeed a string.
-
asInteger
public int asInteger()- Returns:
- the integer value of a number
Json
instance. CallisNumber()
first if you're not sure this instance is indeed a number.
-
asFloat
public float asFloat()- Returns:
- the float value of a float
Json
instance. CallisNumber()
first if you're not sure this instance is indeed a number.
-
asDouble
public double asDouble()- Returns:
- the double value of a number
Json
instance. CallisNumber()
first if you're not sure this instance is indeed a number.
-
asLong
public long asLong()- Returns:
- the long value of a number
Json
instance. CallisNumber()
first if you're not sure this instance is indeed a number.
-
asShort
public short asShort()- Returns:
- the short value of a number
Json
instance. CallisNumber()
first if you're not sure this instance is indeed a number.
-
asByte
public byte asByte()- Returns:
- the byte value of a number
Json
instance. CallisNumber()
first if you're not sure this instance is indeed a number.
-
asChar
public char asChar()- Returns:
- the first character of a string
Json
instance. CallisString()
first if you're not sure this instance is indeed a string.
-
asMap
- Returns:
- 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. CallisObject()
first if you're not sure this instance is indeed aJson
object.
-
asJsonMap
- Returns:
- 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 theJson
object itself. CallisObject()
first if you're not sure this instance is indeed aJson
object.
-
asList
- Returns:
- 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. CallisArray()
first if you're not sure this instance is indeed aJson
array.
-
asJsonList
-
isNull
public boolean isNull()- Returns:
true
if this is aJson
null entity andfalse
otherwise.
-
isString
public boolean isString()- Returns:
true
if this is aJson
string entity andfalse
otherwise.
-
isNumber
public boolean isNumber()- Returns:
true
if this is aJson
number entity andfalse
otherwise.
-
isBoolean
public boolean isBoolean()- Returns:
true
if this is aJson
boolean entity andfalse
otherwise.
-
isArray
public boolean isArray()- Returns:
true
if this is aJson
array (i.e. list) entity andfalse
otherwise.
-
isRaw
public boolean isRaw() -
isObject
public boolean isObject()- Returns:
true
if this is aJson
object entity andfalse
otherwise.
-
isPrimitive
public boolean isPrimitive()- Returns:
true
if this is aJson
primitive entity (one of string, number or boolean) andfalse
otherwise.
-
pad
Json-pad this object as an argument to a callback function.
- Parameters:
callback
- The name of the callback function. Can be null or empty, in which case no padding is done.- Returns:
- The jsonpadded, stringified version of this object if the
callback
is not null or empty, or just the stringified version of the object.
-
collectWithOptions
Return an object representing the complete configuration of a merge. The properties of the object represent paths of the JSON structure being merged and the values represent the set of options that apply to each path.- Parameters:
options
- the configuration options- Returns:
- the configuration object
-
main
-