flexjson
Class JSONSerializer

java.lang.Object
  extended by flexjson.JSONSerializer

public class JSONSerializer
extends Object

JSONSerializer is the main class for performing serialization of Java objects to JSON. JSONSerializer by default performs a shallow serialization. While this might seem strange there is a method to this madness. Shallow serialization allows the developer to control what is serialized out of the object graph. This helps with performance, but more importantly makes good OO possible, fixes the circular reference problem, and doesn't require boiler plate translation code. You don't have to change your object model to make JSON work so it reduces your work load, and keeps you DRY.

Let's go through a simple example:

    JSONSerializer serializer = new JSONSerializer();
    return serializer.serialize( person );
 

What this statement does is output the json from the instance of person. So the JSON we might see for this could look like:

    { "class": "com.mysite.Person",
      "firstname": "Charlie",
      "lastname": "Rose",
      "age", 23
      "birthplace": "Big Sky, Montanna"
    }
 

In this case it's look like it's pretty standard stuff. But, let's say Person had many hobbies (i.e. Person.hobbies is a java.util.List). In this case if we executed the code above we'd still getTransformer the same output. This is a very important feature of flexjson, and that is any instance variable that is a Collection, Map, or Object reference won't be serialized by default. This is what gives flexjson the shallow serialization.

How would we include the hobbies field? Using the include(java.lang.String...) method allows us to include these fields in the serialization process. Here is how we'd do that:

    return new JSONSerializer().include("hobbies").serialize( person );
 

That would produce output like:

    { "class": "com.mysite.Person",
      "firstname": "Charlie",
      "lastname": "Rose",
      "age", 23
      "birthplace": "Big Sky, Montanna",
      "hobbies", [
          "poker",
          "snowboarding",
          "kite surfing",
          "bull riding"
      ]
    }
 

If the hobbies field contained objects, say Hobby instances, then a shallow copy of those objects would be performed. Let's go further and say hobbies had a List of all the people who enjoyed this hobby. This would create a circular reference between Person and Hobby. Since the shallow copy is being performed on Hobby JSONSerialize won't serialize the people field when serializing Hobby instances thus breaking the chain of circular references.

But, for the sake of argument and illustration let's say we wanted to send the people field in Hobby. We can do the following:

    return new JSONSerializer().include("hobbies.people").serialize( person );
 

JSONSerializer is smart enough to know that you want hobbies field included and the people field inside hobbies' instances too. The dot notation allows you do traverse the object graph specifying instance fields. But, remember a shallow copy will stop the code from getting into an infinte loop.

You can also use the exclude method to exclude fields that would be included. Say we have a User object. It would be a serious security risk if we sent the password over the network. We can use the exclude method to prevent the password field from being sent.

   return new JSONSerialize().exclude("password").serialize(user);
 

JSONSerializer will also pay attention to any method or field annotated by JSON. You can include and exclude fields permenantly using the annotation. This is good like in the case of User.password which should never ever be sent through JSON. However, fields like hobbies or favoriteMovies depends on the situation so it's best NOT to annotate those fields, and use the include(java.lang.String...) method.

In a shallow copy only these types of instance fields will be sent: String, Date, Number, Boolean, Character, Enum, Object and null. Subclasses of Object will be serialized except for Collection or Arrays. Anything that would cause a N objects would not be sent. All types will be excluded by default. Fields marked static or transient are not serialized.

Includes and excludes can include wildcards. Wildcards allow you to do things like exclude all class attributes. For example *.class would remove the class attribute that all objects have when serializing. A open ended wildcard like * would cause deep serialization to take place. Be careful with that one. Although you can limit it's depth with an exclude like *.foo. The order of evaluation of includes and excludes is the order in which you called their functions. First call to those functions will cause those expressions to be evaluated first. The first expression to match a path that action will be taken thus short circuiting all other expressions defined later.

Transforers are a new addition that allow you to modify the values that are being serialized. This allows you to create different output for certain conditions. This is very important in web applications. Say you are saving your text to the DB that could contain < and >. If you plan to add that content to your HTML page you'll need to escape those characters. Transformers allow you to do this. Flexjson ships with a simple HTML encoder HtmlEncoderTransformer. Transformers are specified in dot notation just like include and exclude methods, but it doesn't support wildcards.

JSONSerializer is safe to use the serialize() methods from two seperate threads. It is NOT safe to use combination of include(String...) transform(flexjson.transformer.Transformer, String...), or exclude(String...) from multiple threads at the same time. It is also NOT safe to use serialize(Object) and include/exclude/transform from multiple threads. The reason for not making them more thread safe is to boost performance. Typical use case won't call for two threads to modify the JsonSerializer at the same type it's trying to serialize.


Field Summary
static char[] HEX
           
 
Constructor Summary
JSONSerializer()
           
JSONSerializer(TypeTransformerMap defaultTypeTransformers)
           
 
Method Summary
protected  void addExclude(String field)
           
protected  void addInclude(String field)
           
 String deepSerialize(Object target)
          This performs a deep serialization of the target instance.
 String deepSerialize(Object target, OutputHandler out)
          This performs a deep serialization of the target instance and passes the generated JSON into the provided OutputHandler.
 String deepSerialize(Object target, StringBuffer out)
          This performs a deep serialization of the target instance and passes the generated JSON into the provided StringBuffer.
 String deepSerialize(Object target, StringBuilder out)
          This performs a deep serialization of the target instance and passes the generated JSON into the provided StringBuilder.
 void deepSerialize(Object target, Writer out)
          This performs a deep serialization of the target instance and passes the generated JSON into the provided Writer.
 JSONSerializer exclude(String... fields)
          This takes in a dot expression representing fields to exclude when serialize method is called.
 List<PathExpression> getExcludes()
          Return the fields excluded from serialization.
 List<PathExpression> getIncludes()
          Return the fields included in serialization.
 JSONSerializer include(String... fields)
          This takes in a dot expression representing fields to include when serialize method is called.
 JSONSerializer prettyPrint(boolean prettyPrint)
          format output with indentations
 JSONSerializer rootName(String rootName)
          This wraps the resulting JSON in a javascript object that contains a single field named rootName.
 String serialize(Object target)
          This performs a shallow serialization of the target instance.
 String serialize(Object target, OutputHandler out)
          This performs a shallow serialization of the target instance and passes the generated JSON into the provided OutputHandler.
protected  String serialize(Object target, SerializationType serializationType, OutputHandler out)
           
 String serialize(Object target, StringBuffer out)
          This performs a shallow serialization of the target instance and passes the generated JSON into the provided StringBuffer.
 String serialize(Object target, StringBuilder out)
          This performs a shallow serialization of the target instance and passes the generated JSON into the provided StringBuilder.
 void serialize(Object target, Writer out)
          This performs a shallow serialization of the target instance and passes the generated JSON into the provided Writer.
 void setExcludes(List<String> fields)
          Sets the fields excluded in serialization.
 void setIncludes(List<String> fields)
          Sets the fields included in serialization.
 JSONSerializer transform(Transformer transformer, Class... types)
          This adds a Transformer used to manipulate the value of all fields that match the type.
 JSONSerializer transform(Transformer transformer, String... fields)
          This adds a Transformer used to manipulate the value of all the fields you give it.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

HEX

public static final char[] HEX
Constructor Detail

JSONSerializer

public JSONSerializer()

JSONSerializer

public JSONSerializer(TypeTransformerMap defaultTypeTransformers)
Method Detail

prettyPrint

public JSONSerializer prettyPrint(boolean prettyPrint)
format output with indentations

Parameters:
prettyPrint - - should out put cleanfly formatted Json
Returns:
JsonSerializer for chaining configuration

rootName

public JSONSerializer rootName(String rootName)
This wraps the resulting JSON in a javascript object that contains a single field named rootName. This is great to use in conjunction with other libraries like EXTJS whose data models require them to be wrapped in a JSON object.

Parameters:
rootName - - name to assign to root object
Returns:
this JsonSerializer for chaining configurations

serialize

public String serialize(Object target)
This performs a shallow serialization of the target instance. It uses a StringBuilder to write output to.

Parameters:
target - - the instance to serialize to JSON
Returns:
returns JSON as a String

serialize

public void serialize(Object target,
                      Writer out)
This performs a shallow serialization of the target instance and passes the generated JSON into the provided Writer. This can be used to stream JSON back to a browser rather than wait for it to all complete and then dump it all at once like the StringBufferOutputHandler and StringBuilderOutputHandler

Parameters:
target - - the instance to serialize to JSON
out - - Writer to write output to

serialize

public String serialize(Object target,
                        StringBuilder out)
This performs a shallow serialization of the target instance and passes the generated JSON into the provided StringBuilder.

Parameters:
target - - the instance to serialize to JSON
out - - StringBuilder to write output to
Returns:
returns JSON as a String

serialize

public String serialize(Object target,
                        StringBuffer out)
This performs a shallow serialization of the target instance and passes the generated JSON into the provided StringBuffer.

Parameters:
target - - the instance to serialize to JSON
out - - StringBuffer to write output to
Returns:
returns JSON as a String

serialize

public String serialize(Object target,
                        OutputHandler out)
This performs a shallow serialization of the target instance and passes the generated JSON into the provided OutputHandler.

Parameters:
target - - the instance to serialize to JSON
out - - OutputHandler to write output to
Returns:
returns JSON as a String

deepSerialize

public String deepSerialize(Object target)
This performs a deep serialization of the target instance. It will include all collections, maps, and arrays by default so includes are ignored except if you want to include something being excluded by an annotation. Excludes are honored. However, cycles in the target's graph are NOT followed. This means some members won't be included in the JSON if they would create a cycle. Rather than throwing an exception the cycle creating members are simply not followed. This uses a StringBuilder to output JSON to.

Parameters:
target - the instance to serialize to JSON.
Returns:
returns JSON as a String

deepSerialize

public void deepSerialize(Object target,
                          Writer out)
This performs a deep serialization of the target instance and passes the generated JSON into the provided Writer. This can be used to stream JSON back to a browser rather than wait for it to all complete and then dump it all at once like the StringBufferOutputHandler and StringBuilderOutputHandler

Parameters:
target - - the instance to serialize to JSON
out - - Writer

deepSerialize

public String deepSerialize(Object target,
                            StringBuilder out)
This performs a deep serialization of the target instance and passes the generated JSON into the provided StringBuilder.

Parameters:
target - - the instance to serialize to JSON
out - - StringBuilder
Returns:
returns JSON as a String

deepSerialize

public String deepSerialize(Object target,
                            StringBuffer out)
This performs a deep serialization of the target instance and passes the generated JSON into the provided StringBuffer.

Parameters:
target - - the instance to serialize to JSON
out - - StringBuffer
Returns:
returns JSON as a String

deepSerialize

public String deepSerialize(Object target,
                            OutputHandler out)
This performs a deep serialization of the target instance and passes the generated JSON into the provided OutputHandler.

Parameters:
target - - the instance to serialize to JSON
out - - OutputHandler to write to
Returns:
returns JSON as a String

serialize

protected String serialize(Object target,
                           SerializationType serializationType,
                           OutputHandler out)
Parameters:
target - - the instance to serialize to JSON
serializationType - - serialize deep or shallow
out - - output handler
Returns:
returns JSON as a String

transform

public JSONSerializer transform(Transformer transformer,
                                String... fields)
This adds a Transformer used to manipulate the value of all the fields you give it. Fields can be in dot notation just like include(java.lang.String...) and exclude(java.lang.String...) methods. However, transform doesn't support wildcards. Specifying more than one field allows you to add a single instance to multiple fields. It's there for handiness. :-)

Parameters:
transformer - the instance used to transform values
fields - the paths to the fields you want to transform. They can be in dot notation.
Returns:
Hit you back with the JSONSerializer for method chain goodness.

transform

public JSONSerializer transform(Transformer transformer,
                                Class... types)
This adds a Transformer used to manipulate the value of all fields that match the type.

Parameters:
transformer - the instance used to transform values
types - you want to transform.
Returns:
Hit you back with the JSONSerializer for method chain goodness.

addExclude

protected void addExclude(String field)

addInclude

protected void addInclude(String field)

exclude

public JSONSerializer exclude(String... fields)
This takes in a dot expression representing fields to exclude when serialize method is called. You can hand it one or more fields. Example are: "password", "bankaccounts.number", "people.socialsecurity", or "people.medicalHistory". In exclude method dot notations will only exclude the final field (i.e. rightmost field). All the fields to the left of the last field will be included. In order to exclude the medicalHistory field we have to include the people field since people would've been excluded anyway since it's a Collection of Person objects. The order of evaluation is the order in which you call the exclude method. The first call to exclude will be evaluated before other calls to include or exclude. The field expressions are evaluated in order you pass to this method.

Parameters:
fields - one or more field expressions to exclude.
Returns:
this instance for method chaining.

include

public JSONSerializer include(String... fields)
This takes in a dot expression representing fields to include when serialize method is called. You can hand it one or more fields. Examples are: "hobbies", "hobbies.people", "people.emails", or "character.inventory". When using dot notation each field between the dots will be included in the serialization process. The order of evaluation is the order in which you call the include method. The first call to include will be evaluated before other calls to include or exclude. The field expressions are evaluated in order you pass to this method.

Parameters:
fields - one or more field expressions to include.
Returns:
this instance for method chaining.

getIncludes

public List<PathExpression> getIncludes()
Return the fields included in serialization. These fields will be in dot notation.

Returns:
A List of dot notation fields included in serialization.

getExcludes

public List<PathExpression> getExcludes()
Return the fields excluded from serialization. These fields will be in dot notation.

Returns:
A List of dot notation fields excluded from serialization.

setIncludes

public void setIncludes(List<String> fields)
Sets the fields included in serialization. These fields must be in dot notation. This is just here so that JSONSerializer can be treated like a bean so it will integrate with Spring or other frameworks. This is not ment to be used in code use include method for that.

Parameters:
fields - the list of fields to be included for serialization. The fields arg should be a list of strings in dot notation.

setExcludes

public void setExcludes(List<String> fields)
Sets the fields excluded in serialization. These fields must be in dot notation. This is just here so that JSONSerializer can be treated like a bean so it will integrate with Spring or other frameworks. This is not ment to be used in code use exclude method for that.

Parameters:
fields - the list of fields to be excluded for serialization. The fields arg should be a list of strings in dot notation.


Copyright © 2014. All Rights Reserved.