Maven Dependency

<dependency> <groupId>org.apache.juneau</groupId> <artifactId>juneau-marshall</artifactId> <version>9.0-B1</version> </dependency>

Java Library


OSGi Module


The juneau-marshall library includes easy-to-use and highly customizable serializers and parsers based around a common API.

Glossary > Language Support

Features include:

The default serializers can often be used to serialize POJOs in a single line of code:

// A simple bean public class Person { public String name = "John Smith"; public int age = 21; } Person person = new Person(); // An arbitrary POJO // Produces: // "{name:'John Smith',age:21}" String laxJson = SimpleJsonSerializer.DEFAULT.serialize(person); // Produces: // "{"name":"John Smith","age":21}" String strictJson = JsonSerializer.DEFAULT.serialize(person); // Produces: // <object> // <name>John Smith</name> // <age>21</age> // </object> String xml = XmlSerializer.DEFAULT.serialize(person); // Produces: // <table> // <tr><td>name</td><td>John Smith</td></tr> // <tr><td>age</td><td>21</td></tr> // </table> String html = HtmlSerializer.DEFAULT.serialize(person); // Same as Html, but wraps it in HTML and BODY elements with page title/description/links: String htmlDoc = HtmlDocSerializer.DEFAULT.serialize(person); // Produces: // name='John+Smith'&age=21 String urlEncoding = UrlEncodingSerializer.DEFAULT.serialize(person); // Produces: // (name='John Smith',age=21) String uon = UonSerializer.DEFAULT.serialize(person); // Produces: // 82 A4 name AA 4A John Smith 68 A3 age 15 byte[] messagePack = MsgPackSerializer.DEFAULT.serialize(person);

Parsing back into POJOs is equally simple for any of the supported languages shown above. Language fragments are also supported.

JSON parsing shown here:

// Use one of the predefined parsers. ReaderParser parser = JsonParser.DEFAULT; // Parse a JSON object (creates a generic ObjectMap). String json = "{name:'John Smith',age:21}"; Map map = parser.parse(json, Map.class); // Parse a JSON string. json = "'foobar'"; String string = parser.parse(json, String.class); // Parse a JSON number as a Long or Float. json = "123"; Long _long = parser.parse(json, Long.class); Float _float = parser.parse(json, Float.class); // Parse a JSON object as a bean. json = "{name:'John Smith',age:21}"; Person person = parser.parse(json, Person.class); // Parse a JSON object as a HashMap<String,Person>. json = "{a:{name:'John Smith',age:21},b:{name:'Joe Smith',age:42}}"; Map<String,Person> personMap = parser.parse( json, HashMap.class, String.class, Person.class ); // Parse a JSON object as a HashMap<String,LinkedList<Person>>. json = "{a:[{name:'John Smith',age:21},{name:'Joe Smith',age:42}]}"; Map<String,List<Person>> personListMap = parser.parse( json, HashMap.class, String.class, LinkedList.class, Person.class ); // Parse a JSON array of integers as a Collection of Integers or int[] array. json = "[1,2,3]"; List<Integer> integerList = parser.parse( json, LinkedList.class, Integer.class ); int[] intList = parser.parse( json, int[].class ); // Parse arbitrary input into ObjectMap or ObjectList objects // (similar to JSONObject/JSONArray but generalized for all languages). json = "{name:'John Smith',age:21}"; OMap oMap = parser.parse(json, OMap.class); int age = oMap.getInt("age"); json = "[1,true,null]"; OList oList = parser.parse(json, ObjectList.class); boolean boolean = oList.getBoolean(1);

Marshalls are pairings of serializers and parsers in a single class for even simpler code:

Person person = new Person(); // An arbitrary POJO // Serialize String json = Json.DEFAULT.write(person); String simpleJson = SimpleJson.DEFAULT.write(person); String xml = Xml.DEFAULT.write(person); String html = Html.DEFAULT.write(person); String uon = Uon.DEFAULT.write(person); String urlEncoding = UrlEncoding.DEFAULT.write(person); String openapi = OpenApi.DEFAULT.write(person); byte[] msgPack = MsgPack.DEFAULT.write(person); String rdfXml = RdfXml.DEFAULT.write(person); String rdfXmlAbbrev = RdfXmlAbbrev.DEFAULT.write(person); String n3 = N3.DEFAULT.write(person); String nTuple = NTuple.DEFAULT.write(person); String turtle = Turtle.DEFAULT.write(person); // Parse person = Json.DEFAULT.read(json, Person.class); person = Xml.DEFAULT.read(xml, Person.class); person = Html.DEFAULT.read(html, Person.class); person = Uon.DEFAULT.read(uon, Person.class); person = UrlEncoding.DEFAULT.read(urlEncoding, Person.class); person = OpenApi.DEFAULT.read(openapi, Person.class); person = MsgPack.DEFAULT.read(msgPack, Person.class); person = RdfXml.DEFAULT.read(rdfXml, Person.class); person = RdfXmlAbbrev.DEFAULT.read(rdfXmlAbbrev, Person.class); person = N3.DEFAULT.read(n3, Person.class); person = NTuple.DEFAULT.read(nTuple, Person.class); person = Turtle.DEFAULT.read(turtle, Person.class);

Serializers and parsers are builder-based. Build from scratch or clone existing instances. Lots of configuration options available for all the languages.

// Create a serializer from scratch programmatically using a builder. JsonSerializer serializer = JsonSerializer.create() .simple() // Simple mode .sq() // Use single quotes .swaps( // Swap unserializable classes with surrogate POJOs IteratorSwap.class, // Iterators swapped with lists ByteArrayBase64Swap.class, // byte[] swapped with base-64 encoded strings CalendarSwap.ISO8601DT.class // Calendars swapped with ISO8601-compliant strings ) .timeZone(TimeZone.GMT) // For timezone-specific serialization .locale(Locale.JAPAN) // For locale-specific serialization .sortCollections() .sortProperties() .keepNullProperties() .trimStrings() .beanMethodVisibility(PROTECTED) // Control which fields/methods are serialized .dictionary( // Adds type variables for resolution during parsing MyBeanA.class, MyBeanB.class ) .debug() // Debug mode .build(); // Same as above, but using declarative named properties. // This is how serializers and parsers are typically configured on REST servlets and clients. JsonSerializer serializer = JsonSerializer.create() .set(JSON_simpleMode, true) .set(SERIALIZER_quoteChar, '\'') .appendTo(BEAN_swaps, IteratorSwap.class) .appendTo(BEAN_swaps, ByteArrayBase64Swap.class) .appendTo(BEAN_swaps, CalendarSwap.ISO8601DT.class) .set(BEAN_timeZone, TimeZone.GMT) .set(BEAN_locale, Locale.JAPAN) .set(SERIALIZER_sortCollections, true) .set(BEAN_sortProperties, true) .set(SERIALIZER_keepNullProperties, true) .set(SERIALIZER_trimStrings, true) .set(BEAN_beanMethodVisibility, PROTECTED) .appendTo(BEAN_dictionary, MyBeanA.class) .appendTo(BEAN_dictionary, MyBeanB.class) .set(BEAN_debug, true) .build(); // Clone an existing serializer and modify it to use single-quotes. JsonSerializer serializer = JsonSerializer.DEFAULT.builder() .sq() .build();

Many POJOs such as primitives, beans, collections, arrays, and classes with various known constructors and methods are serializable out-of-the-box. For other objects, "transforms" allow you to perform various mutations on them before serialization and after parsing.

UON (URL-Encoded Object Notation) allows JSON-like data structures (OBJECT, ARRAY, NUMBER, BOOLEAN, STRING, NULL) in HTTP constructs (query parameters, form parameters, headers, URL parts) without violating RFC2396. This allows POJOs to be converted directly into these HTTP constructs which is not possible in other languages such as JSON.

( id=1, name='John+Smith', uri=http://sample/addressBook/person/1, addressBookUri=http://sample/addressBook, birthDate=1946-08-12T00:00:00Z, addresses=@( ( uri=http://sample/addressBook/address/1, personUri=http://sample/addressBook/person/1, id=1, street='100+Main+Street', city=Anywhereville, state=NY, zip=12345, isCurrent=true ) ) )

Lots of shortcuts are provided throughout the API to simplify tasks, and the APIs are often useful for debugging and logging purposes as well:

// Create JSON strings from scratch using fluent-style code. String jsonObject = new OMap().append("foo","bar").toString(); String jsonArray = new OList().append("foo").append(123).append(null).toString(); // Create maps and beans directly from JSON. Map<String,Object> myMap = new OMap("{foo:'bar'}"); List<Object> myList = new OList("['foo',123,null]"); // Load a POJO from a JSON file. MyPojo myPojo = JsonParser.DEFAULT.parse(new File("myPojo.json")); // Serialize POJOs and ignore exceptions (great for logging) String json = SimpleJson.DEFAULT.toString(myPojo); // Dump a POJO to the console. SimpleJson.DEFAULT.println(myPojo); String message = new StringMessage("My POJO in {0}: {1}", "JSON", new StringObject(myPojo)).toString(); // Create a 'REST-like' wrapper around a POJO. // Allows you to manipulate POJO trees using URIs and GET/PUT/POST/DELETE commands. PojoRest pojoRest = new PojoRest(myPojo); pojoRest.get(String.class, "addressBook/0/name"); pojoRest.put("addressBook/0/name", "John Smith");

Maven Dependency

<dependency> <groupId>org.apache.juneau</groupId> <artifactId>juneau-marshall-rdf</artifactId> <version>9.0-B1</version> </dependency>

Java Library


OSGi Module


The juneau-marshall-rdf library provides additional serializers and parsers for RDF. These rely on the Apache Jena library to provide support for the following languages:

The serializers and parsers work identically to those in juneau-marshall, but are packaged separately so that you don't need to pull in the Jena dependency unless you need it.

// A simple bean public class Person { public String name = "This is RDF format."; public String id = "foo"; } // Serialize a bean to various RDF languages Person person = new Person(); // Produces: // <rdf:RDF // xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" // xmlns:jp="http://www.apache.org/juneaubp/" // xmlns:j="http://www.apache.org/juneau/"> // <rdf:Description> // <jp:name>This is RDF format.</jp:name> // <jp:id>foo</jp:id> // </rdf:Description> // </rdf:RDF> String rdfXml = RdfXmlAbbrevSerializer.DEFAULT.serialize(person); // Produces: // @prefix jp: <http://www.apache.org/juneaubp/> . // @prefix j: <http://www.apache.org/juneau/> . // [] jp:id "foo" ; // jp:name "This is RDF format." . String rdfN3 = N3Serializer.DEFAULT.serialize(person); // Produces: // _:A3bf53c85X3aX157cf407e2dX3aXX2dX7ffd <http://www.apache.org/juneaubp/name> "This is RDF format." . // _:A3bf53c85X3aX157cf407e2dX3aXX2dX7ffd <http://www.apache.org/juneaubp/age> "rdf" . String rdfNTriple = NTripleSerializer.DEFAULT.serialize(person); // Produces: // @prefix jp: <http://www.apache.org/juneaubp/> . // @prefix j: <http://www.apache.org/juneau/> . // [] jp:id "foo" ; // jp:name "This is RDF format." . String rdfTurtle = TurtleSerializer.DEFAULT.serialize(person);