JSON lib

 

How to use json-lib

Using the JSONSerializer

Working with arrays and collections

Working with objects

Working with XML

Using the JSONSerializer

JSONSerializer can transform any java object to JSON notation and back with a simple and clean interface, leveraging all the builders in JSONObject and JSONArray. To transform a java obect into JSON use JSONSerializer.toJSON(). To transform a valid JSON value (by JSON, I mean an Object implementing that interface), use toJava(). The last method is an instance method because the serializer needs special configuration to transform a JSON value to a bean class, array, List or DynaBean.

Working with arrays and collections

The simplest way to create a JSONArray from a java array or collection is through the static factory methods from JSONArray. JSONArray.fromObject() will inspect its parameter and call the correct factory or constructor.

Examples:

  1. boolean[] boolArray = new boolean[]{true,false,true};  
  2. JSONArray jsonArray = JSONArray.fromObject( boolArray );  
  3. System.out.println( jsonArray );  
  4. // prints [true,false,true]  

boolean[] boolArray = new boolean[]{true,false,true}; JSONArray jsonArray = JSONArray.fromObject( boolArray ); System.out.println( jsonArray ); // prints [true,false,true]

  1. List list = new ArrayList();  
  2. list.add( "first" );  
  3. list.add( "second" );  
  4. JSONArray jsonArray = JSONArray.fromObject( list );  
  5. System.out.println( jsonArray );  
  6. // prints ["first","second"]  

List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray = JSONArray.fromObject( list ); System.out.println( jsonArray ); // prints ["first","second"]

  1. JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );  
  2. System.out.println( jsonArray );  
  3. // prints ["json","is","easy"]  

JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" ); System.out.println( jsonArray ); // prints ["json","is","easy"]

Working with objects

From Beans & Maps to JSON

The simplest way to create a JSONObject from a bean or Map is through the static factory methods from JSONObject. JSONObject.fromObject() will inspect its parameter and call the correct factory or constructor.

Examples:

  1. Map map = new HashMap();  
  2. map.put( "name", "json" );  
  3. map.put( "bool", Boolean.TRUE );  
  4. map.put( "int", new Integer(1) );  
  5. map.put( "arr", new String[]{"a","b"} );  
  6. map.put( "func", "function(i){ return this.arr[i]; }" );  
  7.   
  8. JSONObject jsonObject = JSONObject.fromObject( map );  
  9. System.out.println( jsonObject );  
  10. // prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }]  

Map map = new HashMap(); map.put( "name", "json" ); map.put( "bool", Boolean.TRUE ); map.put( "int", new Integer(1) ); map.put( "arr", new String[]{"a","b"} ); map.put( "func", "function(i){ return this.arr[i]; }" ); JSONObject jsonObject = JSONObject.fromObject( map ); System.out.println( jsonObject ); // prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }]

  1. class MyBean{  
  2.    private String name = "json";  
  3.    private int pojoId = 1;  
  4.    private char[] options = new char[]{'a','f'};  
  5.    private String func1 = "function(i){ return this.options[i]; }";  
  6.    private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");  
  7.   
  8.    // getters & setters  
  9.    ...  
  10. }  
  11.   
  12. JSONObject jsonObject = JSONObject.fromObject( new MyBean() );  
  13. System.out.println( jsonObject );  
  14. /* prints 
  15.   {"name":"json","pojoId":1,"options":["a","f"], 
  16.   "func1":function(i){ return this.options[i];}, 
  17.   "func2":function(i){ return this.options[i];}} 
  18. */  

class MyBean{ private String name = "json"; private int pojoId = 1; private char[] options = new char[]{'a','f'}; private String func1 = "function(i){ return this.options[i]; }"; private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];"); // getters & setters ... } JSONObject jsonObject = JSONObject.fromObject( new MyBean() ); System.out.println( jsonObject ); /* prints {"name":"json","pojoId":1,"options":["a","f"], "func1":function(i){ return this.options[i];}, "func2":function(i){ return this.options[i];}} */

 

CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy.

From JSON to Beans

Json-lib can transform JSONObjects to either a DynaBean or an specific bean class.

When using DynaBean all arrays are converted to Lists, when using an specific bean class the transformation will use type conversion if necessary on array properties.

Convert to DynaBean:

  1. String json = "{name=/"json/",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";  
  2. JSONObject jsonObject = JSONObject.fromObject( json );  
  3. Object bean = JSONObject.toBean( jsonObject );  
  4. assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );  
  5. assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );  
  6. assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );  
  7. assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );  
  8. assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );  
  9. List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );  
  10. Assertions.assertListEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) );  

String json = "{name=/"json/",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; JSONObject jsonObject = JSONObject.fromObject( json ); Object bean = JSONObject.toBean( jsonObject ); assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) ); assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) ); assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) ); assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) ); assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) ); List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) ); Assertions.assertListEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) );

Convert to Bean:

  1. String json = "{bool:true,integer:1,string:/"json/"}";  
  2. JSONObject jsonObject = JSONObject.fromObject( json );  
  3. BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );  
  4. assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) );  
  5. assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) );  
  6. assertEquals( jsonObject.get( "string" ), bean.getString() );  

String json = "{bool:true,integer:1,string:/"json/"}"; JSONObject jsonObject = JSONObject.fromObject( json ); BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class ); assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) ); assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) ); assertEquals( jsonObject.get( "string" ), bean.getString() );

There are two special cases when converting to an specific bean, if the target bean has a Map property and it must contain other beans, JSONObject.toBean() will transform the nested beans into DynaBeans. If you need those nested beans transformed into an specific class, you can either postprocess the Map attribute or provide hints on JSONObject's attributes for conversion. JSONObject.toBean() may be passed a third argument, a Map, that will provide thos hints. Every key must be either the name of a property or a regular expression matching the object's properties, and the value must be a Class.

The second case is similar and it happens when the target bean has a Collection (List) as a property and it must contain other beans. In this case there is no way to provide hints for class conversion. The only possible solution is to postprocess the collection transforming each DynaBean into an specific bean.

To ease the postprocessing scenarios, EZMorph provides a Morpher capable of transforming a DynaBean into an specific bean, BeanMorpher

Example:

  1. class MyBean{  
  2.    private List data;  
  3.    // getters & setters  
  4. }  
  5.   
  6. class Person{  
  7.    private String name;  
  8.    // getters & setters  
  9. }  
  10.   
  11. ...  
  12.   
  13. String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";  
  14. Map classMap = new HashMap();  
  15. classMap.put( "data", Person.class );  
  16. MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );  

class MyBean{ private List data; // getters & setters } class Person{ private String name; // getters & setters } ... String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}"; Map classMap = new HashMap(); classMap.put( "data", Person.class ); MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );

This yields a MyBean instance that has DynaBeans inside the 'data' attribute', so now comes the part of postprocessing, this can be done with an Iterator

Example:

  1. Morpher dynaMorpher = new BeanMorpher( Person.class, JSONUtils.getMorpherRegistry() );  
  2. morpherRegistry.registerMorpher( dynaMorpher );  
  3. List output = new ArrayList();  
  4. for( Iterator i = bean.getData().iterator(); i.hasNext(); ){  
  5.    output.add( morpherRegistry.morph( Person.class, i.next() ) );  
  6. }  
  7. bean.setData( output );  

Morpher dynaMorpher = new BeanMorpher( Person.class, JSONUtils.getMorpherRegistry() ); morpherRegistry.registerMorpher( dynaMorpher ); List output = new ArrayList(); for( Iterator i = bean.getData().iterator(); i.hasNext(); ){ output.add( morpherRegistry.morph( Person.class, i.next() ) ); } bean.setData( output );

To learn more about Morphers, please visit EZMorph's project site.

Working with XML

Working with XML has become easier since version 1.1. Transforming JSONObjects and JSONArrays from and to XML is done through the XMLSerializer.

From JSON to XML

Writing to JSON to XML is as simple as calling XMLSerializer.write(), but there are a lot of options that you may configure to get better control of the XML output. For example you may change the default names for the root element ('o' if object, 'a' if array), the default name for object (an object inside an array is "anonymous"), the default name for array (for the same reason as object), the default name for element (array items have no name). If you'd like to output namescape information but your JSON does not includes it, no problem, you have 8 methods that will let you register and manage namespaces; namespaces defined this way have precedence on any namespace declaration that may be inside the JSON. By default XMLSerializer will append special attributes to each xml element for easing the transformation back to JSON but you may configure it to skip appending those attributes. Any property on a JSONObject that begins with '@' will be treated as an attribute, any property named '#text' will be treated as a Text node.

Please review the javadoc for XMLSerializer to know more about the configurable options.

Code

XML output

  1. JSONObject json = new JSONObject( true );  
  2. String xml = XMLSerializer.write( json );  

JSONObject json = new JSONObject( true ); String xml = XMLSerializer.write( json );

  1. <o class="object" null="true">  
  2.       

<o class="object" null="true">

  1. JSONObject json = JSONObject.fromObject("{/"name/":/"json/",/"bool/":true,/"int/":1}");  
  2. String xml = XMLSerializer.write( json );  

JSONObject json = JSONObject.fromObject("{/"name/":/"json/",/"bool/":true,/"int/":1}"); String xml = XMLSerializer.write( json );

  1. <o class="object">  
  2.    <name type="string">json</name>  
  3.    <bool type="boolean">true</bool>  
  4.    <int type="number">1</int>  
  5. </o>  

<o class="object"> <name type="string">json</name> <bool type="boolean">true</bool> <int type="number">1</int> </o>

  1. JSONArray json = JSONArray.fromObject("[1,2,3]");  
  2. String xml = XMLSerializer.write( json );  

JSONArray json = JSONArray.fromObject("[1,2,3]"); String xml = XMLSerializer.write( json );

  1. <a class="array"<  
  2.    <e type="number">1</e>  
  3.    <e type="number">2</e>  
  4.    <e type="number">3</e>  
  5. </a>  

<a class="array"< <e type="number">1</e> <e type="number">2</e> <e type="number">3</e> </a>

From XML to JSON

XMLSerializer treats each element as a string unless a type parameter is specified.

JSONFunction needs an additional parameter that specifies that function's params.

All xml attributes will have the prefix '@' and text nodes will have the property name '#text'. XMLSerializer supports the rules outlined at Converting Between XML and JSON

XML input

Code

  1. <a class="array">  
  2.   <e type="function" params="i,j">  
  3.       return matrix[i][j];  
  4.   </e>  
  5. </a>  

<a class="array"> <e type="function" params="i,j"> return matrix[i][j]; </e> </a>

  1. JSONArray json = (JSONArray) XMLSerializer.read( xml );  
  2. System.out.println( json );  
  3. // prints [function(i,j){ return matrix[i][j]; }]  

JSONArray json = (JSONArray) XMLSerializer.read( xml ); System.out.println( json ); // prints [function(i,j){ return matrix[i][j]; }]

 

CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy.

 

源文档 <http://json-lib.sourceforge.net/usage.html>

 

Advanced Features

Transforming key names

The JSON spec states that an object key is a String and

A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

This means that you may have a valid JSON key but and invalid Java identifier when transforming form JSON to Java. In order to avoid this problem, Json-lib defines a set of helpers of type JavaIdentifierTransformer that will handle the following cases:

  • JavaIdentifierTransformer.NOOP - will perform no transformation.
  • JavaIdentifierTransformer.STRICT - will throw JSONException if a non JavaIdentifier character is found.
  • JavaIdentifierTransformer.CAMEL_CASE - will use non JavaIdentifier and whitespace characters as word boundaries, capitalizing the first char of a new word.
  • JavaIdentifierTransformer.WHITESPACE - will trim all whitespace and non JavaIdentifier characters from the input string.
  • JavaIdentifierTransformer.UNDERSCORE - will transform all whitespace and non JavaIdentifier characters to '_'.

You may also create and register your own JavaIdentifierTransformers using JsonConfig.setJavaIdentifierTransformer()

Build events

You may recieve events while building an object with the JSONSerializer or the static builder fromObject of JSONObject&JSONArray, all you have to do is enabled event triggering on JsonConfig. The following is a list of events generated by the build process: start/end (object), start/end (array), propertySet( object), elementAdd (array), warning, error.

Skipping transient fields

When building a JSONObject with fromObject or with the JSONSerializer you may skip all transient fields of the source bean, provided that the name of the property returned from the PropertyDescriptor matches the name of the field, meaning that this option will not work if you have a BeanInfo that changes the name of a read method or provides a synthetic property.

Filtering properties

When serializing to JSON there may be some times where you would like to exclude some properties from being processed, the current exclusion mechanism matches the property name to a list of Strings, but what if you would like to filter out all properties that match a regex or extend a particular class? PropertyFilter will help you attain that goal with ease, and what's more, it will also work when converting back to Java. Here is an example filter that will exclude all properties that are a Number when serializing to JSON:

  1. PrimitiveBean bean = new PrimitiveBean();  
  2. JsonConfig jsonConfig = new JsonConfig();  
  3. jsonConfig.setJsonPropertyFilter( new PropertyFilter(){  
  4.    public boolean apply( Object source, String name, Object value ) {  
  5.       if( value != null && Number.class.isAssignableFrom( value.getClass() ) ){  
  6.          return true;  
  7.       }  
  8.       return false;  
  9.    }  
  10. });  
  11. JSONObject json = JSONObject.fromObject( bean, jsonConfig );  

PrimitiveBean bean = new PrimitiveBean(); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter( new PropertyFilter(){ public boolean apply( Object source, String name, Object value ) { if( value != null && Number.class.isAssignableFrom( value.getClass() ) ){ return true; } return false; } }); JSONObject json = JSONObject.fromObject( bean, jsonConfig );

This is another filter example, this time converting back to Java, it will filter out any property named 'bool' or 'integer':

  1. BeanA bean = new BeanA();  
  2. JSONObject json = JSONObject.fromObject( bean );  
  3. JsonConfig jsonConfig = new JsonConfig();  
  4. jsonConfig.setRootClass( BeanA.class );  
  5. jsonConfig.setJavaPropertyFilter( new PropertyFilter(){  
  6.    public boolean apply( Object source, String name, Object value ) {  
  7.       if( "bool".equals( name ) || "integer".equals( name ) ){  
  8.          return true;  
  9.       }  
  10.       return false;  
  11.    }  
  12. });  
  13. BeanA actual = (BeanA) JSONObject.toBean( json, jsonConfig );  

BeanA bean = new BeanA(); JSONObject json = JSONObject.fromObject( bean ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( BeanA.class ); jsonConfig.setJavaPropertyFilter( new PropertyFilter(){ public boolean apply( Object source, String name, Object value ) { if( "bool".equals( name ) || "integer".equals( name ) ){ return true; } return false; } }); BeanA actual = (BeanA) JSONObject.toBean( json, jsonConfig );

Please review the net.sf.json.filters package to find out more about default filters and composite filters.

Selecting the proper JsonBeanProcessor

JsonBeanProcessors are maped to classes but sometimes you'll like that some subclasses may be mapped to the same processor or perhaps you are serializing a recently hydrated instance coming from a database with Hibernate, because the instance's class is not exactly the one you expect (it actually is a cglib proxy class) the default class matching mechanism will not work. In order to solve these problems you may register a JsonBeanProcessorMatcher that will take care of the job of selecting the proper JsonBeanProcessor, just as you need it.

Instantiating non JavaBeans

When serializing from JSON to Java you have to keep one rule in mind, the target class must follow the JavaBeans convention of a no-args constructor but sometimes it won't be possible, as it is the case of java.sql.Timestamp. Json-lib has an option to overcome this "restriction", just register a NewBeanInstanceStrategy into JsonConfig and you are in business.

Changing the default value of a null reference

The JSON spec states that null values can only be assigned to objects, but in Java you can have null assigned to any reference, when Json-lib encounters a null reference it follows these rules

  • value is 0 if the reference is a number (wrapper or primitive)
  • value is '' if the reference is a String, Character or char
  • value is [] if the reference is a Collection or array

But sometimes it would be useful to change that rule, for example instead of assigning 'null' to a null reference of MyBean you would like to assign '{ "empty": true }' because that's what your client code expects. DefaultValueProcessor will let you change that rules, along with DefaultValueProcessorMatcher which will let you select the most appropriate processor, as it is done with JsonBeanProcessors.

Setting properties on beans

JSONObject knows how to set values on a Map or bean when transforming JSON to Java. For those rare ocasions wher you would want to handle the set by yourself you can register a PropertySetStrategy through JsonConfig. This feature comes in handy with map backed beans that are neither a Map nor a DynaBean.

 

源文档 <http://json-lib.sourceforge.net/advanced.html>

 

From Java to JSON

Creating a JSONObject from scratch

  1. JSONObject jsonObject = new JSONObject()  
  2.                               .element( "string", "JSON" )  
  3.                               .element( "integer", "1" )  
  4.                               .element( "double", "2.0" )  
  5.                               .element( "boolean", "true" );  
  6. assertEquals( "JSON", jsonObject.getString("string") );        
  7. assertEquals( 1, jsonObject.getInt("integer") );        
  8. assertEquals( 2.0d, jsonObject.getDouble("double"), 0d );        
  9. assertTrue( jsonObject.getBoolean("boolean") );        

JSONObject jsonObject = new JSONObject() .element( "string", "JSON" ) .element( "integer", "1" ) .element( "double", "2.0" ) .element( "boolean", "true" ); assertEquals( "JSON", jsonObject.getString("string") ); assertEquals( 1, jsonObject.getInt("integer") ); assertEquals( 2.0d, jsonObject.getDouble("double"), 0d ); assertTrue( jsonObject.getBoolean("boolean") ); [Index|From Java to JSON]

Creating a JSONObject from a JSON formatted string

  1. String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";  
  2. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );  
  3. assertEquals( "JSON", jsonObject.getString("string") );        
  4. assertEquals( 1, jsonObject.getInt("integer") );        
  5. assertEquals( 2.0d, jsonObject.getDouble("double"), 0d );        
  6. assertTrue( jsonObject.getBoolean("boolean") );        

String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}"; JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str ); assertEquals( "JSON", jsonObject.getString("string") ); assertEquals( 1, jsonObject.getInt("integer") ); assertEquals( 2.0d, jsonObject.getDouble("double"), 0d ); assertTrue( jsonObject.getBoolean("boolean") ); [Index|From Java to JSON]

Creating a JSONObject from a Map

  1. Map map = new HashMap();  
  2. map.put( "string", "JSON" );  
  3. map.put( "integer", "1" );  
  4. map.put( "double", "2.0" );  
  5. map.put( "boolean", "true" );  
  6. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( map );  
  7. assertEquals( "JSON", jsonObject.getString("string") );        
  8. assertEquals( 1, jsonObject.getInt("integer") );        
  9. assertEquals( 2.0d, jsonObject.getDouble("double"), 0d );        
  10. assertTrue( jsonObject.getBoolean("boolean") );        

Map map = new HashMap(); map.put( "string", "JSON" ); map.put( "integer", "1" ); map.put( "double", "2.0" ); map.put( "boolean", "true" ); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( map ); assertEquals( "JSON", jsonObject.getString("string") ); assertEquals( 1, jsonObject.getInt("integer") ); assertEquals( 2.0d, jsonObject.getDouble("double"), 0d ); assertTrue( jsonObject.getBoolean("boolean") ); [Index|From Java to JSON]

Creating a JSONObject from a JavaBean

  1. public class MyJavaBean {  
  2.    private String string;  
  3.    private int integer;  
  4.    private double dooble;  
  5.    private boolean bool;  
  6.   
  7.    // getters & setters  
  8. }  
  9.   
  10. MyJavaBean bean = new MyJavaBean();  
  11. bean.setString( "JSON" );  
  12. bean.setInteger( 1 );  
  13. bean.setDooble( 2.0d );  
  14. bean.setBool( true );  
  15. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( bean );  
  16. assertEquals( "JSON", jsonObject.getString("string") );        
  17. assertEquals( 1, jsonObject.getInt("integer") );        
  18. assertEquals( 2.0d, jsonObject.getDouble("dooble"), 0d );        
  19. assertTrue( jsonObject.getBoolean("bool") );        

public class MyJavaBean { private String string; private int integer; private double dooble; private boolean bool; // getters & setters } MyJavaBean bean = new MyJavaBean(); bean.setString( "JSON" ); bean.setInteger( 1 ); bean.setDooble( 2.0d ); bean.setBool( true ); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( bean ); assertEquals( "JSON", jsonObject.getString("string") ); assertEquals( 1, jsonObject.getInt("integer") ); assertEquals( 2.0d, jsonObject.getDouble("dooble"), 0d ); assertTrue( jsonObject.getBoolean("bool") ); [Index|From Java to JSON]

Creating a JSONArray from scratch

  1. JSONArray jsonArray = new JSONArray()  
  2.                               .element( "JSON" )  
  3.                               .element( "1" )  
  4.                               .element( "2.0" )  
  5.                               .element( "true" );  
  6. assertEquals( "JSON", jsonArray.getString(0) );        
  7. assertEquals( 1, jsonArray.getInt(1) );        
  8. assertEquals( 2.0d, jsonArray.getDouble(2), 0d );        
  9. assertTrue( jsonArray.getBoolean(3) );        

JSONArray jsonArray = new JSONArray() .element( "JSON" ) .element( "1" ) .element( "2.0" ) .element( "true" ); assertEquals( "JSON", jsonArray.getString(0) ); assertEquals( 1, jsonArray.getInt(1) ); assertEquals( 2.0d, jsonArray.getDouble(2), 0d ); assertTrue( jsonArray.getBoolean(3) ); [Index|From Java to JSON]

Creating a JSONArray from a JSON formatted string

  1. String str = "['JSON', 1, 2.0, true]";  
  2. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str );  
  3. assertEquals( "JSON", jsonArray.getString(0) );        
  4. assertEquals( 1, jsonArray.getInt(1) );        
  5. assertEquals( 2.0d, jsonArray.getDouble(2), 0d );        
  6. assertTrue( jsonArray.getBoolean(3) );        

String str = "['JSON', 1, 2.0, true]"; JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str ); assertEquals( "JSON", jsonArray.getString(0) ); assertEquals( 1, jsonArray.getInt(1) ); assertEquals( 2.0d, jsonArray.getDouble(2), 0d ); assertTrue( jsonArray.getBoolean(3) ); [Index|From Java to JSON]

Creating a JSONArray from a Collection

  1. List list = new ArrayList();  
  2. list.add( "JSON" );  
  3. list.add( "1" );  
  4. list.add( "2.0" );  
  5. list.add( "true" );  
  6. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( list );  
  7. assertEquals( "JSON", jsonArray.getString(0) );        
  8. assertEquals( 1, jsonArray.getInt(1) );        
  9. assertEquals( 2.0d, jsonArray.getDouble(2), 0d );        
  10. assertTrue( jsonArray.getBoolean(3) );        

List list = new ArrayList(); list.add( "JSON" ); list.add( "1" ); list.add( "2.0" ); list.add( "true" ); JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( list ); assertEquals( "JSON", jsonArray.getString(0) ); assertEquals( 1, jsonArray.getInt(1) ); assertEquals( 2.0d, jsonArray.getDouble(2), 0d ); assertTrue( jsonArray.getBoolean(3) ); [Index|From Java to JSON]

Creating a JSONArray from an array

  1. Object[] array = new Object[]{ "JSON", "1", "2.0", "true" };  
  2. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( array );  
  3. assertEquals( "JSON", jsonArray.getString(0) );        
  4. assertEquals( 1, jsonArray.getInt(1) );        
  5. assertEquals( 2.0d, jsonArray.getDouble(2), 0d );        
  6. assertTrue( jsonArray.getBoolean(3) );        

Object[] array = new Object[]{ "JSON", "1", "2.0", "true" }; JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( array ); assertEquals( "JSON", jsonArray.getString(0) ); assertEquals( 1, jsonArray.getInt(1) ); assertEquals( 2.0d, jsonArray.getDouble(2), 0d ); assertTrue( jsonArray.getBoolean(3) ); [Index|From Java to JSON]

JavaScript functions

  1. String str = "{'func': function( param ){ doSomethingWithParam(param); }}";  
  2. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );  
  3. JSONFunction func = (JSONFunction) jsonObject.get("func");  
  4. ArrayAssertions.assertEquals( new String[]{"param"}, func.getParams() );  
  5. assertEquals( "doSomethingWithParam(param);", func.getText() );  

String str = "{'func': function( param ){ doSomethingWithParam(param); }}"; JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str ); JSONFunction func = (JSONFunction) jsonObject.get("func"); ArrayAssertions.assertEquals( new String[]{"param"}, func.getParams() ); assertEquals( "doSomethingWithParam(param);", func.getText() ); [Index|From Java to JSON]

Exclude properties

  1. String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";  
  2. JsonConfig jsonConfig = new JsonConfig();  
  3. jsonConfig.setExcludes( new String[]{ "double", "boolean" } );  
  4. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str, jsonConfig );  
  5. assertEquals( "JSON", jsonObject.getString("string") );        
  6. assertEquals( 1, jsonObject.getInt("integer") );        
  7. assertFalse( jsonObject.has("double") );     
  8. assertFalse( jsonObject.has("boolean") );     

String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}"; JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes( new String[]{ "double", "boolean" } ); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str, jsonConfig ); assertEquals( "JSON", jsonObject.getString("string") ); assertEquals( 1, jsonObject.getInt("integer") ); assertFalse( jsonObject.has("double") ); assertFalse( jsonObject.has("boolean") ); [Index|From Java to JSON]

Exclude properties (with filters)

  1. String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";  
  2. JsonConfig jsonConfig = new JsonConfig();  
  3. jsonConfig.setJsonPropertyFilter( new PropertyFilter(){    
  4.    public boolean apply( Object source, String name, Object value ) {    
  5.       if( "double".equals(value) || "boolean".equals(value) ){    
  6.          return true;    
  7.       }    
  8.       return false;    
  9.    }    
  10. });    
  11. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str, jsonConfig );  
  12. assertEquals( "JSON", jsonObject.getString("string") );        
  13. assertEquals( 1, jsonObject.getInt("integer") );        
  14. assertFalse( jsonObject.has("double") );     
  15. assertFalse( jsonObject.has("boolean") );     

String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}"; JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter( new PropertyFilter(){ public boolean apply( Object source, String name, Object value ) { if( "double".equals(value) || "boolean".equals(value) ){ return true; } return false; } }); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str, jsonConfig ); assertEquals( "JSON", jsonObject.getString("string") ); assertEquals( 1, jsonObject.getInt("integer") ); assertFalse( jsonObject.has("double") ); assertFalse( jsonObject.has("boolean") ); [Index|From Java to JSON]

From JSON to Java

JSONObject to DynaBean

  1. String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";  
  2. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );  
  3. DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );  
  4. assertEquals( "JSON", bean.get("string") );        
  5. assertEquals( new Integer(1), bean.get("integer") );        
  6. assertEquals( new Double(2.0), bean.get("double") );        
  7. assertEquals( Boolean.TRUE, bean.get("boolean") );     

String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}"; JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str ); DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject ); assertEquals( "JSON", bean.get("string") ); assertEquals( new Integer(1), bean.get("integer") ); assertEquals( new Double(2.0), bean.get("double") ); assertEquals( Boolean.TRUE, bean.get("boolean") ); [Index|From JSON to Java]

JSONObject to JavaBean

  1. public class MyJavaBean {  
  2.    private String string;  
  3.    private int integer;  
  4.    private double dooble;  
  5.    private boolean bool;  
  6.   
  7.    // getters & setters  
  8. }  
  9.   
  10. MyJavaBean bean = new MyJavaBean();  
  11. bean.setString( "JSON" );  
  12. bean.setInteger( 1 );  
  13. bean.setDooble( 2.0d );  
  14. bean.setBool( true );  
  15. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( bean );  
  16. JsonConfig jsonConfig = new JsonConfig();  
  17. jsonConfig.setRootClass( MyJavaBean.class );  
  18. MyJavaBean bean2 = (MyJavaBean) JSONSerializer.toJava( jsonObject, jsonConfig );  
  19. assertNotNull( bean2 );  
  20. assertEquals( "JSON", bean2.getString() );  
  21. assertEquals( 1, bean2.getInteger() );  
  22. assertEquals( 2.0d, bean2.getDooble(), 0d );  
  23. assertTrue( bean2.getBool() );  

public class MyJavaBean { private String string; private int integer; private double dooble; private boolean bool; // getters & setters } MyJavaBean bean = new MyJavaBean(); bean.setString( "JSON" ); bean.setInteger( 1 ); bean.setDooble( 2.0d ); bean.setBool( true ); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( bean ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( MyJavaBean.class ); MyJavaBean bean2 = (MyJavaBean) JSONSerializer.toJava( jsonObject, jsonConfig ); assertNotNull( bean2 ); assertEquals( "JSON", bean2.getString() ); assertEquals( 1, bean2.getInteger() ); assertEquals( 2.0d, bean2.getDooble(), 0d ); assertTrue( bean2.getBool() ); [Index|From JSON to Java]

JSONArray to List

  1. List input = new ArrayList();  
  2. input.add( "JSON" );  
  3. input.add( "1" );  
  4. input.add( "2.0" );  
  5. input.add( "true" );  
  6. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
  7. List output = (List) JSONSerializer.toJava( jsonArray );  
  8. ArrayAssertions.assertEquals( input, output );  

List input = new ArrayList(); input.add( "JSON" ); input.add( "1" ); input.add( "2.0" ); input.add( "true" ); JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input ); List output = (List) JSONSerializer.toJava( jsonArray ); ArrayAssertions.assertEquals( input, output ); [Index|From JSON to Java]

JSONArray to array

  1. List input = new ArrayList();  
  2. input.add( "JSON" );  
  3. input.add( "1" );  
  4. input.add( "2.0" );  
  5. input.add( "true" );  
  6. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
  7. JsonConfig jsonConfig = new JsonConfig();  
  8. jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
  9. Object[] output = (Object[]) JSONSerializer.toJava( jsonArray, jsonConfig );  
  10. Object[] expected = new Object[]{ "JSON", "1", "2.0", "true" };  
  11. ArrayAssertions.assertEquals( expected, output);  

List input = new ArrayList(); input.add( "JSON" ); input.add( "1" ); input.add( "2.0" ); input.add( "true" ); JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY ); Object[] output = (Object[]) JSONSerializer.toJava( jsonArray, jsonConfig ); Object[] expected = new Object[]{ "JSON", "1", "2.0", "true" }; ArrayAssertions.assertEquals( expected, output); [Index|From JSON to Java]

JSONArray to array (type conversion)

  1. List input = new ArrayList();  
  2. input.add( "1" );  
  3. input.add( "2" );  
  4. input.add( "3.0" );  
  5. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
  6. JsonConfig jsonConfig = new JsonConfig();  
  7. jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
  8. jsonConfig.setRootClass( Integer.TYPE );  
  9. int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  
  10. int[] expected = new int[]{ 1, 2, 3 };  
  11. ArrayAssertions.assertEquals( expected, output);  

List input = new ArrayList(); input.add( "1" ); input.add( "2" ); input.add( "3.0" ); JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY ); jsonConfig.setRootClass( Integer.TYPE ); int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig ); int[] expected = new int[]{ 1, 2, 3 }; ArrayAssertions.assertEquals( expected, output); [Index|From JSON to Java]

JSONObject to JavaBean, exclude properties with filters

  1. public class MyJavaBean {  
  2.    private String string;  
  3.    private int integer;  
  4.    private double dooble = 0d;  
  5.    private boolean bool;  
  6.   
  7.    // getters & setters  
  8. }  
  9.   
  10. MyJavaBean bean = new MyJavaBean();  
  11. bean.setString( "JSON" );  
  12. bean.setInteger( 1 );  
  13. bean.setDooble( 2.0d );  
  14. bean.setBool( true );  
  15. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( bean );  
  16. JsonConfig jsonConfig = new JsonConfig();  
  17. jsonConfig.setRootClass( MyJavaBean.class );  
  18. jsonConfig.setJavaPropertyFilter( new PropertyFilter(){    
  19.    public boolean apply( Object source, String name, Object value ) {    
  20.       if( "bool".equals( name ) || "dooble".equals( name ) ){    
  21.          return true;    
  22.       }    
  23.       return false;    
  24.    }    
  25. });   
  26. MyJavaBean bean2 = (MyJavaBean) JSONSerializer.toJava( jsonObject, jsonConfig );  
  27. assertNotNull( bean2 );  
  28. assertEquals( "JSON", bean2.getString() );  
  29. assertEquals( 1, bean2.getInteger() );  
  30. assertEquals( 0d, bean2.getDooble(), 0d );  
  31. assertFalse( bean2.getBool() );  

public class MyJavaBean { private String string; private int integer; private double dooble = 0d; private boolean bool; // getters & setters } MyJavaBean bean = new MyJavaBean(); bean.setString( "JSON" ); bean.setInteger( 1 ); bean.setDooble( 2.0d ); bean.setBool( true ); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( bean ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( MyJavaBean.class ); jsonConfig.setJavaPropertyFilter( new PropertyFilter(){ public boolean apply( Object source, String name, Object value ) { if( "bool".equals( name ) || "dooble".equals( name ) ){ return true; } return false; } }); MyJavaBean bean2 = (MyJavaBean) JSONSerializer.toJava( jsonObject, jsonConfig ); assertNotNull( bean2 ); assertEquals( "JSON", bean2.getString() ); assertEquals( 1, bean2.getInteger() ); assertEquals( 0d, bean2.getDooble(), 0d ); assertFalse( bean2.getBool() ); [Index|From JSON to Java]

From JSON to XML

JSONObject to XML

  1. String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. String xml = xmlSerializer.write( json );  
  5. System.out.println(xml);  

String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <o>  
  3.    <boolean type="boolean">true</boolean>  
  4.    <double type="number">2.0</double>  
  5.    <integer type="number">1</integer>  
  6.    <name type="string">JSON</name>  
  7.    <nested class="object">  
  8.       <id type="number">42</id>  
  9.    </nested>  
  10.    <array class="array">  
  11.       <e type="number">1</e>  
  12.       <e type="number">2</e>  
  13.       <e type="number">3</e>  
  14.    </array>  
  15. </o>  

<?xml version="1.0" encoding="UTF-8"?> <o> <boolean type="boolean">true</boolean> <double type="number">2.0</double> <integer type="number">1</integer> <name type="string">JSON</name> <nested class="object"> <id type="number">42</id> </nested> <array class="array"> <e type="number">1</e> <e type="number">2</e> <e type="number">3</e> </array> </o> [Index|From JSON to XML]

JSONObject to XML (no type hints)

  1. String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. xmlSerializer.setTypeHintsEnabled( false );  
  5. String xml = xmlSerializer.write( json );  
  6. System.out.println(xml);  

String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsEnabled( false ); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <o>  
  3.    <boolean>true</boolean>  
  4.    <double>2.0</double>  
  5.    <integer>1</integer>  
  6.    <name>JSON</name>  
  7.    <nested>  
  8.       <id>42</id>  
  9.    </nested>  
  10.    <array>  
  11.       <e>1</e>  
  12.       <e>2</e>  
  13.       <e>3</e>  
  14.    </nested>  
  15. </o>  

<?xml version="1.0" encoding="UTF-8"?> <o> <boolean>true</boolean> <double>2.0</double> <integer>1</integer> <name>JSON</name> <nested> <id>42</id> </nested> <array> <e>1</e> <e>2</e> <e>3</e> </nested> </o> [Index|From JSON to XML]

JSONObject to XML (with json prefix)

  1. String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. xmlSerializer.setTypeHintsCompatibility( false );  
  5. String xml = xmlSerializer.write( json );  
  6. System.out.println(xml);  

String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsCompatibility( false ); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <o>  
  3.    <boolean json_type="boolean">true</boolean>  
  4.    <double json_type="number">2.0</double>  
  5.    <integer json_type="number">1</integer>  
  6.    <name json_type="string">JSON</name>  
  7.    <nested json_class="object">  
  8.       <id json_type="number">42</id>  
  9.    </nested>  
  10.    <array json_class="array">  
  11.       <e json_type="number">1</e>  
  12.       <e json_type="number">2</e>  
  13.       <e json_type="number">3</e>  
  14.    </array>  
  15. </o>  

<?xml version="1.0" encoding="UTF-8"?> <o> <boolean json_type="boolean">true</boolean> <double json_type="number">2.0</double> <integer json_type="number">1</integer> <name json_type="string">JSON</name> <nested json_class="object"> <id json_type="number">42</id> </nested> <array json_class="array"> <e json_type="number">1</e> <e json_type="number">2</e> <e json_type="number">3</e> </array> </o> [Index|From JSON to XML]

JSONObject to XML (change node names)

  1. String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. xmlSerializer.setRootName( "root" );  
  5. xmlSerializer.setElementName( "element" );  
  6. String xml = xmlSerializer.write( json );  
  7. System.out.println(xml);  

String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setRootName( "root" ); xmlSerializer.setElementName( "element" ); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <root>  
  3.    <boolean type="boolean">true</boolean>  
  4.    <double type="number">2.0</double>  
  5.    <integer type="number">1</integer>  
  6.    <name type="string">JSON</name>  
  7.    <nested class="object">  
  8.       <id type="number">42</id>  
  9.    </nested>  
  10.    <array class="array">  
  11.       <element type="number">1</e>  
  12.       <element type="number">2</e>  
  13.       <element type="number">3</e>  
  14.    </array>  
  15. </root>  

<?xml version="1.0" encoding="UTF-8"?> <root> <boolean type="boolean">true</boolean> <double type="number">2.0</double> <integer type="number">1</integer> <name type="string">JSON</name> <nested class="object"> <id type="number">42</id> </nested> <array class="array"> <element type="number">1</e> <element type="number">2</e> <element type="number">3</e> </array> </root> [Index|From JSON to XML]

JSONArray to XML

  1. String str = "['JSON', 1, 2.0, true, {'id':42}, [1,2,3]]";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. String xml = xmlSerializer.write( json );  
  5. System.out.println(xml);  

String str = "['JSON', 1, 2.0, true, {'id':42}, [1,2,3]]"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <a>  
  3.    <e type="string">JSON</e>  
  4.    <e type="number">1</e>  
  5.    <e type="number">2.0</e>  
  6.    <e type="boolean">true</e>  
  7.    <e class="object">  
  8.       <id type="number">42</id>  
  9.    </e>  
  10.    <e class="array">  
  11.       <e type="number">1</e>  
  12.       <e type="number">2</e>  
  13.       <e type="number">3</e>  
  14.    </e>  
  15. </a>  

<?xml version="1.0" encoding="UTF-8"?> <a> <e type="string">JSON</e> <e type="number">1</e> <e type="number">2.0</e> <e type="boolean">true</e> <e class="object"> <id type="number">42</id> </e> <e class="array"> <e type="number">1</e> <e type="number">2</e> <e type="number">3</e> </e> </a> [Index|From JSON to XML]

JSONArray to XML (no type hints)

  1. String str = "['JSON', 1, 2.0, true, {'id':42}, [1,2,3]]";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. xmlSerializer.setTypeHintsEnabled( false );  
  5. String xml = xmlSerializer.write( json );  
  6. System.out.println(xml);  

String str = "['JSON', 1, 2.0, true, {'id':42}, [1,2,3]]"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsEnabled( false ); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <a>  
  3.    <e>JSON</e>  
  4.    <e>1</e>  
  5.    <e>2.0</e>  
  6.    <e>true</e>  
  7.    <e>  
  8.       <id>42</id>  
  9.    </e>  
  10.    <e>  
  11.       <e>1</e>  
  12.       <e>2</e>  
  13.       <e>3</e>  
  14.    </e>  
  15. </a>  

<?xml version="1.0" encoding="UTF-8"?> <a> <e>JSON</e> <e>1</e> <e>2.0</e> <e>true</e> <e> <id>42</id> </e> <e> <e>1</e> <e>2</e> <e>3</e> </e> </a> [Index|From JSON to XML]

JSONArray to XML (with json prefix)

  1. String str = "['JSON', 1, 2.0, true, {'id':42}, [1,2,3]]";  
  2. JSON json = JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. xmlSerializer.setTypeHintsCompatibility( false );  
  5. String xml = xmlSerializer.write( json );  
  6. System.out.println(xml);  

String str = "['JSON', 1, 2.0, true, {'id':42}, [1,2,3]]"; JSON json = JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsCompatibility( false ); String xml = xmlSerializer.write( json ); System.out.println(xml);

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <a>  
  3.    <e json_type="string">JSON</e>  
  4.    <e json_type="number">1</e>  
  5.    <e json_type="number">2.0</e>  
  6.    <e json_type="boolean">true</e>  
  7.    <e json_class="object">  
  8.       <id json_type="number">42</id>  
  9.    </e>  
  10.    <e json_class="array">  
  11.       <e json_type="number">1</e>  
  12.       <e json_type="number">2</e>  
  13.       <e json_type="number">3</e>  
  14.    </e>  
  15. </a>  

<?xml version="1.0" encoding="UTF-8"?> <a> <e json_type="string">JSON</e> <e json_type="number">1</e> <e json_type="number">2.0</e> <e json_type="boolean">true</e> <e json_class="object"> <id json_type="number">42</id> </e> <e json_class="array"> <e json_type="number">1</e> <e json_type="number">2</e> <e json_type="number">3</e> </e> </a> [Index|From JSON to XML]

Flatten JSONArray into parent

  1. String str = "{'number': [1,2,3]}";  
  2. JSONObject json = (JSONObject) JSONSerializer.toJSON( str );  
  3. XMLSerializer xmlSerializer = new XMLSerializer();  
  4. xmlSerializer.setTypeHintsEnabled( false );  
  5. String xml = xmlSerializer.write( json );  
  6. System.out.println( xml );  
  7. json.getJSONArray( "number" ).setExpandElements( true );  
  8. xml = xmlSerializer.write( json );  
  9. System.out.println( xml );  

String str = "{'number': [1,2,3]}"; JSONObject json = (JSONObject) JSONSerializer.toJSON( str ); XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsEnabled( false ); String xml = xmlSerializer.write( json ); System.out.println( xml ); json.getJSONArray( "number" ).setExpandElements( true ); xml = xmlSerializer.write( json ); System.out.println( xml );

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <o>  
  3.    <number>  
  4.       <e>1</e>  
  5.       <e>2</e>  
  6.       <e>3</e>  
  7.    </number>  
  8. </o>  
  9.   
  10. <?xml version="1.0" encoding="UTF-8"?>  
  11. <o>  
  12.    <number>1</number>  
  13.    <number>2</number>  
  14.    <number>3</number>  
  15. </o>  

<?xml version="1.0" encoding="UTF-8"?> <o> <number> <e>1</e> <e>2</e> <e>3</e> </number> </o> <?xml version="1.0" encoding="UTF-8"?> <o> <number>1</number> <number>2</number> <number>3</number> </o> [Index|From JSON to XML]

From XML to JSON

XML to JSONObject

  1. <o number="1">  
  2.    first  
  3.    <string>json</string>  
  4.    <array>  
  5.       <e>1</e>  
  6.       <e>true</e>  
  7.    </array>  
  8. </o>  

<o number="1"> first <string>json</string> <array> <e>1</e> <e>true</e> </array> </o>

  1. String xml = ...  
  2. XMLSerializer xmlSerializer = new XMLSerializer();  
  3. JSON json = xmlSerializer.read( xml );  
  4. System.out.println( json.toString(2) );  

String xml = ... XMLSerializer xmlSerializer = new XMLSerializer(); JSON json = xmlSerializer.read( xml ); System.out.println( json.toString(2) );

  1. {  
  2.   "string": "json",  
  3.   "#text": "first",  
  4.   "array":   [  
  5.     "1",  
  6.     "true"  
  7.   ],  
  8.   "@number": "1"  
  9. }  

{ "string": "json", "#text": "first", "array": [ "1", "true" ], "@number": "1" } [Index|From XML to JSON]

Groovy Support

Using the JsonGroovyBuilder

The following snippets produce the same JSON output

  1. def builder = new JsonGroovyBuilder()  
  2. def books = builder.books {  
  3.    book = [title: "Groovy in Action", author: "Dierk Konig"]  
  4.    book = [title: "Groovy in Action", author: "Dierk Konig"]  
  5. }  

def builder = new JsonGroovyBuilder() def books = builder.books { book = [title: "Groovy in Action", author: "Dierk Konig"] book = [title: "Groovy in Action", author: "Dierk Konig"] }

  1. def builder = new JsonGroovyBuilder()  
  2. def books = builder.books {  
  3.    book = new Book(title: "Groovy in Action", author: "Dierk Konig")  
  4. }  

def builder = new JsonGroovyBuilder() def books = builder.books { book = new Book(title: "Groovy in Action", author: "Dierk Konig") }

  1. def builder = new JsonGroovyBuilder()  
  2. def books = builder.books {  
  3.    book = {  
  4.       title = "Groovy in Action"  
  5.       author= "Dierk Konig"  
  6.    }  
  7.    book = {  
  8.       title = "Groovy in Action"  
  9.       author= "Dierk Konig"  
  10.    }  
  11. }  

def builder = new JsonGroovyBuilder() def books = builder.books { book = { title = "Groovy in Action" author= "Dierk Konig" } book = { title = "Groovy in Action" author= "Dierk Konig" } }

  1. def builder = new JsonGroovyBuilder()  
  2. def books = builder.books {  
  3.    2.times {  
  4.       book = {  
  5.          title = "Groovy in Action"  
  6.          author= "Dierk Konig"  
  7.       }  
  8.    }  
  9. }  

def builder = new JsonGroovyBuilder() def books = builder.books { 2.times { book = { title = "Groovy in Action" author= "Dierk Konig" } } }

  1. def builder = new JsonGroovyBuilder()  
  2. def books = builder.books {  
  3.    2.times {  
  4.       book {  
  5.          title = "Groovy in Action"  
  6.          author= "Dierk Konig"  
  7.       }  
  8.    }  
  9. }  

def builder = new JsonGroovyBuilder() def books = builder.books { 2.times { book { title = "Groovy in Action" author= "Dierk Konig" } } }

  1. def builder = new JsonGroovyBuilder()  
  2. def books = builder.books {  
  3.    book {  
  4.       title = "Groovy in Action"  
  5.       author= "Dierk Konig"  
  6.    }  
  7.    book {  
  8.       title = "Groovy in Action"  
  9.       author= "Dierk Konig"  
  10.    }  
  11. }  

def builder = new JsonGroovyBuilder() def books = builder.books { book { title = "Groovy in Action" author= "Dierk Konig" } book { title = "Groovy in Action" author= "Dierk Konig" } }

  1. {  
  2.    "books": {  
  3.       "book": [  
  4.          {  
  5.         "title": "Groovy in Action",  
  6.         "author": "Dierk Konig"  
  7.      },  
  8.          {  
  9.         "title": "Groovy in Action",  
  10.         "author": "Dierk Konig"  
  11.      }  
  12.       ]  
  13.    }  
  14. }  

{ "books": { "book": [ { "title": "Groovy in Action", "author": "Dierk Konig" }, { "title": "Groovy in Action", "author": "Dierk Konig" } ] } } [Index|Groovy Support]

JRuby Support

Creating a JSONObject

  1. json = JSONObject.new  
  2. json.element("string","json").element("bool",true)  
  3. json["integer"] = 1  
  4. assert_equal "json", json["string"]           
  5. assert_equal true, json["bool"]           
  6. assert_equal 1, json["integer"]    

json = JSONObject.new json.element("string","json").element("bool",true) json["integer"] = 1 assert_equal "json", json["string"] assert_equal true, json["bool"] assert_equal 1, json["integer"] [Index|JRuby Support]

Append elements to JSONObject with << (array)

  1. json = JSONObject.new  
  2. json && ["key","value"]  
  3. assert !json.empty?  
  4. assert_equal "value", json["key"]  

json = JSONObject.new json && ["key","value"] assert !json.empty? assert_equal "value", json["key"] [Index|JRuby Support]

Append elements to JSONObject with << (hash)

  1. json = JSONObject.new  
  2. json & {"key1" => "value1", "key2" => "value2" }  
  3. assert !json.empty?  
  4. assert_equal 2, json.size()  
  5. assert_equal "value1", json["key1"]  
  6. assert_equal "value2", json["key2"]  

 

源文档 <http://json-lib.sourceforge.net/snippets.html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值