Class Json
- java.lang.Object
-
- mjson.Json
-
- All Implemented Interfaces:
Serializable
public class Json extends Object implements 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
Jsoninstances. 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 runtimeUnsupportedOperationException. 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
Jsonwith one of theisXXXmethods:isObject(),isArray(),isNumber(),isBoolean(),isString(),isNull().The underlying representation of a given
Jsoninstance can be obtained by calling the genericgetValue()method or one of theasXXXmethods such asasBoolean()orasString()etc. JSON objects are represented as JavaMaps while JSON arrays are represented as JavaLists. Because those are mutable aggregate structures, there are two versions of the correspondingasXXXmethods:asMap()which performs a deep copy of the underlying map, unwrapping every nested Json entity to its Java representation andasJsonMap()which simply return the map reference. Similarly there areasList()andasJsonList().Constructing and Modifying JSON Structures
There are several static factory methods in this class that allow you to create new
Jsoninstances:Factory static methods read(String)Parse a JSON string and return the resulting Jsoninstance. 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 Jsonitself.nil()Return a Jsoninstance representing JSONnull.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 aJsonvalue.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 theJson.Factoryinterface and configure it either globally with thesetGlobalFactory(Factory)method or on a per-thread basis with theattachFactory(Factory)/detachFactory()methods.If a
Jsoninstance is an object, you can set its properties by calling theset(String, Object)method which will add a new property or replace an existing one. Adding elements to an arrayJsonis done with theadd(Object)method. Removing elements by their index (or key) is done with thedelAt(int)(ordelAt(String)) method. You can also remove an element from an array without knowing its index with theremove(Object)method. All these methods return theJsoninstance 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, callatDel(int)oratDel(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 theat(String)method does the same for a property of an object instance. You can use theat(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 theis(String, Object)andis(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
Jsoninstances 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 thepad(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 aJson.Schemausing the factory methodJson.Schemaand then call itsvalidatemethod 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);- Version:
- 1.4.2
- Author:
- Borislav Iordanov
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classJson.DefaultFactorystatic interfaceJson.FactoryThis interface defines howJsoninstances are constructed.static interfaceJson.Function<T,R>static classJson.helpExposes some internal methods that are useful forJson.Factoryimplementations or other extension/layers of the library.static classJson.MalformedJsonExceptionstatic interfaceJson.SchemaRepresents JSON schema - a specific data format that a JSON entity must follow.
-
Field Summary
Fields Modifier and Type Field Description static Json.FactorydefaultFactory
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description Jsonadd(Object anything)Add an arbitrary Java object to thisJsonarray.Jsonadd(Json el)Add the specifiedJsonelement to this array.static Jsonarray()static Jsonarray(Object... args)Return a new JSON array filled up with the list of arguments.booleanasBoolean()byteasByte()charasChar()doubleasDouble()floatasFloat()intasInteger()List<Json>asJsonList()Map<String,Json>asJsonMap()List<Object>asList()longasLong()Map<String,Object>asMap()shortasShort()StringasString()Jsonat(int index)Return theJsonelement at the specified index of thisJsonarray.Jsonat(String property)Return the specified property of aJsonobject ornullif there's no such property.Jsonat(String property, Object def)Return the specified property of aJsonobject if it exists.Jsonat(String property, Json def)Return the specified property of aJsonobject if it exists.JsonatDel(int index)Remove the element at the specified index from aJsonarray and return that element.JsonatDel(String property)Remove the specified property from aJsonobject and return that property.static voidattachFactory(Json.Factory factory)Attach a thread-local JsonJson.Factoryto be used specifically by this thread.voidattachTo(Json enclosing)Explicitly set the parent of this element.protected JsoncollectWithOptions(Json... options)Return an object representing the complete configuration of a merge.JsondelAt(int index)Remove the element at the specified index from aJsonarray.JsondelAt(String property)Delete the specified property from aJsonobject.static voiddetachFactory()Clear the thread-local factory previously attached to this thread via theattachFactory(Factory)method.Jsondup()static Json.Factoryfactory()Return theJson.Factorycurrently in effect.ObjectgetValue()booleanhas(String property)Return true if thisJsonobject has the specified property and false otherwise.booleanis(int index, Object value)Returntrueif and only if thisJsonarray has an element with the specified value at the specified index.booleanis(String property, Object value)Returntrueif and only if thisJsonobject has a property with the specified value.booleanisArray()booleanisBoolean()booleanisNull()booleanisNumber()booleanisObject()booleanisPrimitive()booleanisString()static Jsonmake(Object anything)Convert an arbitrary Java instance to aJsoninstance.static Jsonnil()static Jsonobject()static Jsonobject(Object... args)Return a new JSON object initialized from the passed list of name/value pairs.Stringpad(String callback)Json-pad this object as an argument to a callback function.static Jsonread(String jsonAsString)Parse a JSON entity from its string representation.static Jsonread(URL location)Parse a JSON entity from aURL.static Jsonread(CharacterIterator it)Parse a JSON entity from aCharacterIterator.Jsonremove(Object anything)Remove the specified Java object (converted to a Json instance) from aJsonarray.Jsonremove(Json el)Remove the specified element from aJsonarray.static Json.Schemaschema(URI uri)static Json.Schemaschema(URI uri, Json.Function<URI,Json> relativeReferenceResolver)static Json.Schemaschema(Json S)static Json.Schemaschema(Json S, URI uri)Jsonset(int index, Object value)Change the value of a JSON array element.Jsonset(String property, Object value)Set aJsonobjects's property.Jsonset(String property, Json value)Set aJsonobjects's property.static voidsetGlobalFactory(Json.Factory factory)Specify a global JsonJson.Factoryto be used by all threads that don't have a specific thread-local factory attached to them.StringtoString(int maxCharacters)Return a string representation ofthisthat does not exceed a certain maximum length.Jsonup()Deprecated.This method is problematic and underused and it will be soon removed.Jsonwith(Json object, Object... options)Same aswith each option argument converted towith(Json,Json...options)Jsonfirst.Jsonwith(Json object, Json[] options)Combine this object or array with the passed in object or array.
-
-
-
Field Detail
-
defaultFactory
public static final Json.Factory defaultFactory
-
-
Constructor Detail
-
Json
protected Json()
-
Json
protected Json(Json enclosing)
-
-
Method Detail
-
schema
public static Json.Schema schema(Json S)
-
schema
public static Json.Schema schema(URI uri)
-
schema
public static Json.Schema schema(URI uri, Json.Function<URI,Json> relativeReferenceResolver)
-
schema
public static Json.Schema schema(Json S, URI uri)
-
factory
public static Json.Factory factory()
Return the
Json.Factorycurrently 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
-
setGlobalFactory
public static void setGlobalFactory(Json.Factory factory)
Specify a global Json
Json.Factoryto be used by all threads that don't have a specific thread-local factory attached to them.- Parameters:
factory- The new global factory
-
attachFactory
public static void attachFactory(Json.Factory factory)
Attach a thread-local Json
Json.Factoryto be used specifically by this thread. Thread-local Json factories are the only means to have differentJson.Factoryimplementations 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
public static Json read(String jsonAsString)
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
public static Json read(URL location)
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
public static Json read(CharacterIterator it)
Parse a JSON entity from a
CharacterIterator.- Parameters:
it- A character iterator.- Returns:
- the parsed JSON element
- See Also:
read(String)
-
nil
public static Json nil()
- Returns:
- the
null Jsoninstance.
-
object
public static Json object()
- Returns:
- a newly constructed, empty JSON object.
-
object
public static Json object(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
toStringmethod. Each value is first converted to aJsoninstance using themake(Object)method.- Parameters:
args- A sequence of name value pairs.- Returns:
- the new JSON object.
-
array
public static Json array()
- Returns:
- a new constructed, empty JSON array.
-
array
public static Json array(Object... args)
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
public static Json make(Object anything)
Convert an arbitrary Java instance to a
Jsoninstance.Maps, Collections and arrays are recursively copied where each of their elements concerted into
Jsoninstances as well. The keys of aMapparameter are normally strings, but anything with a meaningfultoStringimplementation 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 anIllegalArgumentExceptionif it doesn't know how to convert the argument to aJsoninstance. - Throws:
IllegalArgumentException- when the concrete type of the parameter is unknown.
-
toString
public String toString(int maxCharacters)
Return a string representation of
thisthat 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.
-
attachTo
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.Factorywith your own implementations of the Json types.- Parameters:
enclosing- The parent element.
-
up
public final Json up()
Deprecated.This method is problematic and underused and it will be soon removed.- Returns:
- the
Jsonentity, if any, enclosing thisJson. The returned value can benullor aJsonobject or list, but not one of the primitive types.
-
dup
public Json dup()
- Returns:
- a clone (a duplicate) of this
Jsonentity. 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
public Json at(int index)
Return the
Jsonelement at the specified index of thisJsonarray. 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
public Json at(String property)
Return the specified property of a
Jsonobject ornullif 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
public final Json at(String property, Json def)
Return the specified property of a
Jsonobject if it exists. If it doesn't, then create a new property with value thedefparameter 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.- Returns:
- The JSON element that is the value of that property or the
defparameter if the value does not exist.
-
at
public final Json at(String property, Object def)
Return the specified property of a
Jsonobject if it exists. If it doesn't, then create a new property with value thedefparameter 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.- Returns:
- The JSON element that is the value of that property or
def.
-
has
public boolean has(String property)
Return true if this
Jsonobject has the specified property and false otherwise.- Parameters:
property- The name of the property.- Returns:
trueif this is JSON object which has the specified property andfalseif it is a JSON object which does NOT have that property.- Throws:
UnsupportedOperationException- if this is not a JSON object.
-
is
public boolean is(String property, Object value)
Return
trueif and only if thisJsonobject has a property with the specified value. In particular, if the object has no such propertyfalseis 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:
- if this is a JSON object and it has the specified property
.equalsto the specifiedvalue. - Throws:
UnsupportedOperationException- if this is not a JSON object.
-
is
public boolean is(int index, Object value)Return
trueif and only if thisJsonarray has an element with the specified value at the specified index. In particular, if the array has no element at this index,falseis 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:
- if this is a JSON array and it has the specified element at
indexwhich.equalsto the specifiedvalue. - Throws:
UnsupportedOperationException- if this is not a JSON array.
-
add
public Json add(Json el)
Add the specified
Jsonelement to this array.- Parameters:
el- The JSON element to add to this array.- Returns:
- this
- Throws:
UnsupportedOperationException- if this is not a JSON array.
-
add
public final Json add(Object anything)
Add an arbitrary Java object to this
Jsonarray. The object is first converted to aJsoninstance by calling the staticmake(java.lang.Object)method.- Parameters:
anything- Any Java object that can be converted to a Json instance.- Returns:
- this
-
atDel
public Json atDel(String property)
Remove the specified property from a
Jsonobject and return that property.- Parameters:
property- The property to be removed.- Returns:
- The property value or
nullif the object didn't have such a property to begin with.
-
atDel
public Json atDel(int index)
Remove the element at the specified index from a
Jsonarray and return that element.- Parameters:
index- The index of the element to delete.- Returns:
- The element value.
-
delAt
public Json delAt(String property)
Delete the specified property from a
Jsonobject.- Parameters:
property- The property to be removed.- Returns:
- this
-
delAt
public Json delAt(int index)
Remove the element at the specified index from a
Jsonarray.- Parameters:
index- The index of the element to delete.- Returns:
- this
-
remove
public Json remove(Json el)
Remove the specified element from a
Jsonarray.- Parameters:
el- The element to delete.- Returns:
- this
-
remove
public final Json remove(Object anything)
Remove the specified Java object (converted to a Json instance) from a
Jsonarray. This is equivalent toremove(.make(Object))- Parameters:
anything- The object to delete.- Returns:
- this
-
set
public Json set(String property, Json value)
Set a
Jsonobjects's property.- Parameters:
property- The property name.value- The value of the property.- Returns:
- this
-
set
public final Json set(String property, Object value)
Set a
Jsonobjects's property.- Parameters:
property- The property name.value- The value of the property, converted to aJsonrepresentation withmake(java.lang.Object).- Returns:
- this
-
set
public Json set(int index, Object value)
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
public Json with(Json object, Json[] options)
Combine this object or array with the passed in object or array. The types of
thisand theobjectargument must match. If both areJsonobjects, 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
public Json with(Json object, Object... options)
Same aswith each option argument converted towith(Json,Json...options)Jsonfirst.- Parameters:
object- the other JSON object the properties of which will be stored into this object, overwriting any existing properties with conflicting names.options- a set of options, as arbitrary Java objects, converted to JSON via themake(Object)method.- Returns:
this
-
getValue
public Object getValue()
- Returns:
- the underlying value of this
Jsonentity. 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
Jsoninstance. CallisBoolean()first if you're not sure this instance is indeed a boolean.
-
asString
public String asString()
- Returns:
- the string value of a string
Jsoninstance. CallisString()first if you're not sure this instance is indeed a string.
-
asInteger
public int asInteger()
- Returns:
- the integer value of a number
Jsoninstance. CallisNumber()first if you're not sure this instance is indeed a number.
-
asFloat
public float asFloat()
- Returns:
- the float value of a float
Jsoninstance. CallisNumber()first if you're not sure this instance is indeed a number.
-
asDouble
public double asDouble()
- Returns:
- the double value of a number
Jsoninstance. CallisNumber()first if you're not sure this instance is indeed a number.
-
asLong
public long asLong()
- Returns:
- the long value of a number
Jsoninstance. CallisNumber()first if you're not sure this instance is indeed a number.
-
asShort
public short asShort()
- Returns:
- the short value of a number
Jsoninstance. CallisNumber()first if you're not sure this instance is indeed a number.
-
asByte
public byte asByte()
- Returns:
- the byte value of a number
Jsoninstance. CallisNumber()first if you're not sure this instance is indeed a number.
-
asChar
public char asChar()
- Returns:
- the first character of a string
Jsoninstance. CallisString()first if you're not sure this instance is indeed a string.
-
asMap
public Map<String,Object> asMap()
- Returns:
- a map of the properties of an object
Jsoninstance. 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 aJsonobject.
-
asJsonMap
public Map<String,Json> asJsonMap()
- Returns:
- the underlying map of properties of a
Jsonobject. The returned map is the actual object representation so any modifications to it are modifications of theJsonobject itself. CallisObject()first if you're not sure this instance is indeed aJsonobject.
-
asList
public List<Object> asList()
- Returns:
- a list of the elements of a
Jsonarray. 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 aJsonarray.
-
isNull
public boolean isNull()
- Returns:
trueif this is aJsonnull entity andfalseotherwise.
-
isString
public boolean isString()
- Returns:
trueif this is aJsonstring entity andfalseotherwise.
-
isNumber
public boolean isNumber()
- Returns:
trueif this is aJsonnumber entity andfalseotherwise.
-
isBoolean
public boolean isBoolean()
- Returns:
trueif this is aJsonboolean entity andfalseotherwise.
-
isArray
public boolean isArray()
- Returns:
trueif this is aJsonarray (i.e. list) entity andfalseotherwise.
-
isObject
public boolean isObject()
- Returns:
trueif this is aJsonobject entity andfalseotherwise.
-
isPrimitive
public boolean isPrimitive()
- Returns:
trueif this is aJsonprimitive entity (one of string, number or boolean) andfalseotherwise.
-
pad
public String pad(String callback)
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
callbackis not null or empty, or just the stringified version of the object.
-
collectWithOptions
protected Json collectWithOptions(Json... options)
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
-
-