Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /* Jackson JSON-processor.
    *
    * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
    *
    * Licensed under the License specified in file LICENSE, included with
    * the source code and binary code bundles.
    * You may not use this file except in compliance with the License.
    *
    * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  package com.fasterxml.jackson.core;
  
  import java.io.*;
  import java.net.URL;
  
The main factory class of Jackson package, used to configure and construct reader (aka parser, JsonParser) and writer (aka generator, JsonGenerator) instances.

Factory instances are thread-safe and reusable after configuration (if any). Typically applications and services use only a single globally shared factory instance, unless they need differently configured factories. Factory reuse is important if efficiency matters; most recycling of expensive construct is done on per-factory basis.

Creation of a factory instance is a light-weight operation, and since there is no need for pluggable alternative implementations (as there is no "standard" JSON processor API to implement), the default constructor is used for constructing factory instances.

Author(s):
Tatu Saloranta
  
  public class JsonFactory
      implements Versioned,
          java.io.Serializable // since 2.1 (for Android, mostly)
  {
    
Computed for Jackson 2.1.0 release
  
      private static final long serialVersionUID = 8726401676402117450L;

    
Name used to identify JSON format (and returned by getFormatName()
  
      public final static String FORMAT_NAME_JSON = "JSON";
    
    
Bitfield (set of flags) of all factory features that are enabled by default.
  
      protected final static int DEFAULT_FACTORY_FEATURE_FLAGS = JsonFactory.Feature.collectDefaults();

    
Bitfield (set of flags) of all parser features that are enabled by default.
  
      protected final static int DEFAULT_PARSER_FEATURE_FLAGS = JsonParser.Feature.collectDefaults();
    
    
Bitfield (set of flags) of all generator features that are enabled by default.
  
      protected final static int DEFAULT_GENERATOR_FEATURE_FLAGS = JsonGenerator.Feature.collectDefaults();
  
Enumeration that defines all on/off features that can only be changed for JsonFactory.
  
      public enum Feature {
          
          // // // Symbol handling (interning etc)
          
        
Feature that determines whether JSON object field names are to be canonicalized using java.lang.String.intern() or not: if enabled, all field names will be intern()ed (and caller can count on this being true for all such names); if disabled, no intern()ing is done. There may still be basic canonicalization (that is, same String will be used to represent all identical object property names for a single document).

Note: this setting only has effect if CANONICALIZE_FIELD_NAMES is true -- otherwise no canonicalization of any sort is done.

This setting is enabled by default.

 
         INTERN_FIELD_NAMES(true),

        
Feature that determines whether JSON object field names are to be canonicalized (details of how canonicalization is done then further specified by INTERN_FIELD_NAMES).

This setting is enabled by default.

 
         CANONICALIZE_FIELD_NAMES(true)
 
         ;

        
Whether feature is enabled or disabled by default.
 
         private final boolean _defaultState;
        
        
Method that calculates bit set (flags) of all features that are enabled by default.
 
         public static int collectDefaults()
         {
             int flags = 0;
             for (Feature f : values()) {
                 if (f.enabledByDefault()) {
                     flags |= f.getMask();
                 }
             }
             return flags;
         }
         
         private Feature(boolean defaultState)
         {
              = defaultState;
         }
         
         public boolean enabledByDefault() { return ; }
 
         public boolean enabledIn(int flags) { return (flags & getMask()) != 0; }
         
         public int getMask() { return (1 << ordinal()); }
     }    
     /*
     /**********************************************************
     /* Buffer, symbol table management
     /**********************************************************
      */

    
This ThreadLocal contains a java.lang.ref.SoftReference to a com.fasterxml.jackson.core.util.BufferRecycler used to provide a low-cost buffer recycling between reader and writer instances.
 
     final protected static ThreadLocal<SoftReference<BufferRecycler>> _recyclerRef
         = new ThreadLocal<SoftReference<BufferRecycler>>();

    
Each factory comes equipped with a shared root symbol table. It should not be linked back to the original blueprint, to avoid contents from leaking between factories.
 
     protected final transient CharsToNameCanonicalizer _rootCharSymbols = CharsToNameCanonicalizer.createRoot();

    
Alternative to the basic symbol table, some stream-based parsers use different name canonicalization method.

TODO: should clean up this; looks messy having 2 alternatives with not very clear differences.

 
     protected final transient BytesToNameCanonicalizer _rootByteSymbols = BytesToNameCanonicalizer.createRoot();
 
     /*
     /**********************************************************
     /* Configuration
     /**********************************************************
      */

    
Object that implements conversion functionality between Java objects and JSON content. For base JsonFactory implementation usually not set by default, but can be explicitly set. Sub-classes (like

Link:
org.codehaus.jackson.map.MappingJsonFactory} usually provide an implementation.
 
     protected ObjectCodec _objectCodec;

    
Currently enabled factory features.
 
     protected int _factoryFeatures = ;
    
    
Currently enabled parser features.
 
     protected int _parserFeatures = ;

    
Currently enabled generator features.
 
     protected int _generatorFeatures = ;

    
Definition of custom character escapes to use for generators created by this factory, if any. If null, standard data format specific escapes are used.
 
     protected CharacterEscapes _characterEscapes;

    
Optional helper object that may decorate input sources, to do additional processing on input during parsing.
 
     protected InputDecorator _inputDecorator;

    
Optional helper object that may decorate output object, to do additional processing on output during content generation.
 
     protected OutputDecorator _outputDecorator;

    
Separator used between root-level values, if any; null indicates "do not add separator". Default separator is a single space character.

Since:
2.1
 
     
     /*
     /**********************************************************
     /* Construction
     /**********************************************************
      */
    
    
Default constructor used to create factory instances. Creation of a factory instance is a light-weight operation, but it is still a good idea to reuse limited number of factory instances (and quite often just a single instance): factories are used as context for storing some reused processing objects (such as symbol tables parsers use) and this reuse only works within context of a single factory instance.
 
     public JsonFactory() { this(null); }
 
     public JsonFactory(ObjectCodec oc) {  = oc; }

    
Method for constructing a new JsonFactory that has the same settings as this instance, but is otherwise independent (i.e. nothing is actually shared, symbol tables are separate). Note that ObjectCodec reference is not copied but is set to null; caller typically needs to set it after calling this method.

Since:
2.1
 
     public JsonFactory copy()
     {
         _checkInvalidCopy(JsonFactory.class);
         return new JsonFactory(null);
     }

    

Parameters:
exp
Since:
2.1
 
     protected void _checkInvalidCopy(Class<?> exp)
     {
         if (getClass() != exp) {
             throw new IllegalStateException("Failed copy(): "+getClass().getName()
                     +" (version: "+version()+") does not override copy(); it has to");
         }
     }
 
     /*
     /**********************************************************
     /* Serializable overrides
     /**********************************************************
      */

    
Method that we need to override to actually make restoration go through constructors etc. Also: must be overridden by sub-classes as well.
 
     protected Object readResolve() {
         return new JsonFactory();
     }
     
     /*
     /**********************************************************
     /* Format detection functionality (since 1.8)
     /**********************************************************
      */

    
Method that can be used to quickly check whether given schema is something that parsers and/or generators constructed by this factory could use. Note that this means possible use, at the level of data format (i.e. schema is for same data format as parsers and generators this factory constructs); individual schema instances may have further usage restrictions.

Since:
2.1
 
     public boolean canUseSchema(FormatSchema schema) {
         String ourFormat = getFormatName();
         return (ourFormat != null) && ourFormat.equals(schema.getSchemaType());
     }

    
Method that returns short textual id identifying format this factory supports.

Note: sub-classes should override this method; default implementation will return null for all sub-classes

 
     public String getFormatName()
     {
         /* Somewhat nasty check: since we can't make this abstract
          * (due to backwards compatibility concerns), need to prevent
          * format name "leakage"
          */
         if (getClass() == JsonFactory.class) {
             return ;
         }
         return null;
     }
 
     public MatchStrength hasFormat(InputAccessor accthrows IOException
     {
         // since we can't keep this abstract, only implement for "vanilla" instance
         if (getClass() == JsonFactory.class) {
             return hasJSONFormat(acc);
         }
         return null;
     }

    
Method that can be called to determine if a custom ObjectCodec is needed for binding data parsed using JsonParser constructed by this factory (which typically also implies the same for serialization with JsonGenerator).

Returns:
True if custom codec is needed with parsers and generators created by this factory; false if a general ObjectCodec is enough
Since:
2.1
 
     public boolean requiresCustomCodec() {
         return false;
     }
    
    
Helper method that can be called to determine if content accessed using given accessor seems to be JSON content.
 
     protected MatchStrength hasJSONFormat(InputAccessor accthrows IOException
     {
         return ByteSourceJsonBootstrapper.hasJSONFormat(acc);
     }
 
     /*
     /**********************************************************
     /* Versioned
     /**********************************************************
      */
 
 //  @Override
     public Version version() {
         return ..version();
     }
 
     /*
     /**********************************************************
     /* Configuration, factory features
     /**********************************************************
      */

    
Method for enabling or disabling specified parser feature (check JsonParser.Feature for list of features)
 
     public final JsonFactory configure(JsonFactory.Feature fboolean state) {
         return state ? enable(f) : disable(f);
     }

    
Method for enabling specified parser feature (check JsonFactory.Feature for list of features)
 
     public JsonFactory enable(JsonFactory.Feature f) {
          |= f.getMask();
         return this;
     }

    
Method for disabling specified parser features (check JsonFactory.Feature for list of features)
 
     public JsonFactory disable(JsonFactory.Feature f) {
          &= ~f.getMask();
         return this;
     }

    
Checked whether specified parser feature is enabled.
 
     public final boolean isEnabled(JsonFactory.Feature f) {
         return ( & f.getMask()) != 0;
     }
     
     /*
     /**********************************************************
     /* Configuration, parser configuration
     /**********************************************************
      */
    
    
Method for enabling or disabling specified parser feature (check JsonParser.Feature for list of features)
 
     public final JsonFactory configure(JsonParser.Feature fboolean state) {
         return state ? enable(f) : disable(f);
     }

    
Method for enabling specified parser feature (check JsonParser.Feature for list of features)
 
     public JsonFactory enable(JsonParser.Feature f) {
          |= f.getMask();
         return this;
     }

    
Method for disabling specified parser features (check JsonParser.Feature for list of features)
 
     public JsonFactory disable(JsonParser.Feature f) {
          &= ~f.getMask();
         return this;
     }

    
Checked whether specified parser feature is enabled.
 
     public final boolean isEnabled(JsonParser.Feature f) {
         return ( & f.getMask()) != 0;
     }

    
Method for getting currently configured input decorator (if any; there is no default decorator).
 
     public InputDecorator getInputDecorator() {
         return ;
     }

    
Method for overriding currently configured input decorator
 
          = d;
         return this;
     }
     
     /*
     /**********************************************************
     /* Configuration, generator settings
     /**********************************************************
      */

    
Method for enabling or disabling specified generator feature (check JsonGenerator.Feature for list of features)
 
     public final JsonFactory configure(JsonGenerator.Feature fboolean state) {
         return state ? enable(f) : disable(f);
     }


    
Method for enabling specified generator features (check JsonGenerator.Feature for list of features)
 
     public JsonFactory enable(JsonGenerator.Feature f) {
          |= f.getMask();
         return this;
     }

    
Method for disabling specified generator feature (check JsonGenerator.Feature for list of features)
 
     public JsonFactory disable(JsonGenerator.Feature f) {
          &= ~f.getMask();
         return this;
     }

    
Check whether specified generator feature is enabled.
 
     public final boolean isEnabled(JsonGenerator.Feature f) {
         return ( & f.getMask()) != 0;
     }

    
Method for accessing custom escapes factory uses for JsonGenerators it creates.
 
         return ;
     }

    
Method for defining custom escapes factory uses for JsonGenerators it creates.
 
          = esc;
         return this;
     }

    
Method for getting currently configured output decorator (if any; there is no default decorator).
 
     public OutputDecorator getOutputDecorator() {
         return ;
     }

    
Method for overriding currently configured output decorator
 
          = d;
         return this;
     }

    
Method that allows overriding String used for separating root-level JSON values (default is single space character)

Parameters:
sep Separator to use, if any; null means that no separator is automatically added
Since:
2.1
 
     public JsonFactory setRootValueSeparator(String sep) {
          = (sep == null) ? null : new SerializedString(sep);
         return this;
     }

    

Since:
2.1
 
     public String getRootValueSeparator() {
         return ( == null) ? null : .getValue();
     }
     
     /*
     /**********************************************************
     /* Configuration, other
     /**********************************************************
      */

    
Method for associating a ObjectCodec (typically a com.fasterxml.jackson.databind.ObjectMapper) with this factory (and more importantly, parsers and generators it constructs). This is needed to use data-binding methods of JsonParser and JsonGenerator instances.
 
     public JsonFactory setCodec(ObjectCodec oc) {
          = oc;
         return this;
     }
 
     public ObjectCodec getCodec() { return ; }
 
     /*
     /**********************************************************
     /* Parser factories (new ones, as per [Issue-25])
     /**********************************************************
      */

    
Method for constructing JSON parser instance to parse contents of specified file. Encoding is auto-detected from contents according to JSON specification recommended mechanism.

Underlying input stream (needed for reading contents) will be owned (and managed, i.e. closed as need be) by the parser, since caller has no access to it.

Parameters:
f File that contains JSON content to parse
Since:
2.1
 
     public JsonParser createParser(File f)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(f);
     }

    
Method for constructing JSON parser instance to parse contents of resource reference by given URL. Encoding is auto-detected from contents according to JSON specification recommended mechanism.

Underlying input stream (needed for reading contents) will be owned (and managed, i.e. closed as need be) by the parser, since caller has no access to it.

Parameters:
url URL pointing to resource that contains JSON content to parse
Since:
2.1
 
     public JsonParser createParser(URL url)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(url);
     }

    
Method for constructing JSON parser instance to parse the contents accessed via specified input stream.

The input stream will not be owned by the parser, it will still be managed (i.e. closed if end-of-stream is reacher, or parser close method called) if (and only if) JsonParser.Feature.AUTO_CLOSE_SOURCE is enabled.

Note: no encoding argument is taken since it can always be auto-detected as suggested by JSON RFC.

Parameters:
in InputStream to use for reading JSON content to parse
Since:
2.1
 
     public JsonParser createParser(InputStream in)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(in);
     }

    
Method for constructing parser for parsing the contents accessed via specified Reader.

The read stream will not be owned by the parser, it will still be managed (i.e. closed if end-of-stream is reacher, or parser close method called) if (and only if) JsonParser.Feature.AUTO_CLOSE_SOURCE is enabled.

Parameters:
r Reader to use for reading JSON content to parse
Since:
2.1
 
     public JsonParser createParser(Reader r)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(r);
     }

    
Method for constructing parser for parsing the contents of given byte array.

Since:
2.1
 
     public JsonParser createParser(byte[] data)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(data);
     }

    
Method for constructing parser for parsing the contents of given byte array.

Parameters:
data Buffer that contains data to parse
offset Offset of the first data byte within buffer
len Length of contents to parse within buffer
Since:
2.1
 
     public JsonParser createParser(byte[] dataint offsetint len)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(dataoffsetlen);
     }

    
Method for constructing parser for parsing contents of given String.

Since:
2.1
 
     public JsonParser createParser(String content)
         throws IOExceptionJsonParseException
     {
         // Must delegate to old version, until 2.2
         // TODO: change direction in 2.2; after ensuring impls support new method
         return createJsonParser(content);
     }
 
     /*
     /**********************************************************
     /* Parser factories (old ones, as per [Issue-25])
     /**********************************************************
      */

    
Method for constructing JSON parser instance to parse contents of specified file. Encoding is auto-detected from contents according to JSON specification recommended mechanism.

Underlying input stream (needed for reading contents) will be owned (and managed, i.e. closed as need be) by the parser, since caller has no access to it.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

Parameters:
f File that contains JSON content to parse
 
     public JsonParser createJsonParser(File f)
         throws IOExceptionJsonParseException
     {
         // true, since we create InputStream from File
         IOContext ctxt = _createContext(ftrue);
         InputStream in = new FileInputStream(f);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             in = .decorate(ctxtin);
         }
         return _createParser(inctxt);
     }

    
Method for constructing JSON parser instance to parse contents of resource reference by given URL. Encoding is auto-detected from contents according to JSON specification recommended mechanism.

Underlying input stream (needed for reading contents) will be owned (and managed, i.e. closed as need be) by the parser, since caller has no access to it.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

Parameters:
url URL pointing to resource that contains JSON content to parse
 
     public JsonParser createJsonParser(URL url)
         throws IOExceptionJsonParseException
     {
         // true, since we create InputStream from URL
         IOContext ctxt = _createContext(urltrue);
         InputStream in = _optimizedStreamFromURL(url);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             in = .decorate(ctxtin);
         }
         return _createParser(inctxt);
     }

    
Method for constructing JSON parser instance to parse the contents accessed via specified input stream.

The input stream will not be owned by the parser, it will still be managed (i.e. closed if end-of-stream is reacher, or parser close method called) if (and only if) JsonParser.Feature.AUTO_CLOSE_SOURCE is enabled.

Note: no encoding argument is taken since it can always be auto-detected as suggested by JSON RFC.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

Parameters:
in InputStream to use for reading JSON content to parse
 
         throws IOExceptionJsonParseException
     {
         IOContext ctxt = _createContext(infalse);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             in = .decorate(ctxtin);
         }
         return _createParser(inctxt);
     }

    
Method for constructing parser for parsing the contents accessed via specified Reader.

The read stream will not be owned by the parser, it will still be managed (i.e. closed if end-of-stream is reacher, or parser close method called) if (and only if) JsonParser.Feature.AUTO_CLOSE_SOURCE is enabled.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

Parameters:
r Reader to use for reading JSON content to parse
 
     public JsonParser createJsonParser(Reader r)
         throws IOExceptionJsonParseException
     {
         // false -> we do NOT own Reader (did not create it)
         IOContext ctxt = _createContext(rfalse);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             r = .decorate(ctxtr);
         }
         return _createParser(rctxt);
     }

    
Method for constructing parser for parsing the contents of given byte array.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

 
     public JsonParser createJsonParser(byte[] data)
         throws IOExceptionJsonParseException
     {
         IOContext ctxt = _createContext(datatrue);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             InputStream in = .decorate(ctxtdata, 0, data.length);
             if (in != null) {
                 return _createParser(inctxt);
             }
         }
         return _createParser(data, 0, data.lengthctxt);
     }

    
Method for constructing parser for parsing the contents of given byte array.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

Parameters:
data Buffer that contains data to parse
offset Offset of the first data byte within buffer
len Length of contents to parse within buffer
 
     public JsonParser createJsonParser(byte[] dataint offsetint len)
         throws IOExceptionJsonParseException
     {
         IOContext ctxt = _createContext(datatrue);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             InputStream in = .decorate(ctxtdataoffsetlen);
             if (in != null) {
                 return _createParser(inctxt);
             }
         }
 	return _createParser(dataoffsetlenctxt);
     }

    
Method for constructing parser for parsing contents of given String.

NOTE: as of 2.1, should not be used (will be deprecated in 2.2); instead, should call createParser.

 
     public JsonParser createJsonParser(String content)
         throws IOExceptionJsonParseException
     {
         Reader r = new StringReader(content);
         // true -> we own the Reader (and must close); not a big deal
         IOContext ctxt = _createContext(rtrue);
         // [JACKSON-512]: allow wrapping with InputDecorator
         if ( != null) {
             r = .decorate(ctxtr);
         }
         return _createParser(rctxt);
     }
 
     /*
     /**********************************************************
     /* Generator factories, new (as per [Issue-25]
     /**********************************************************
      */

    
Method for constructing JSON generator for writing JSON content using specified output stream. Encoding to use must be specified, and needs to be one of available types (as per JSON specification).

Underlying stream is NOT owned by the generator constructed, so that generator will NOT close the output stream when JsonGenerator.close() is called (unless auto-closing feature, JsonGenerator.Feature.AUTO_CLOSE_TARGET is enabled). Using application needs to close it explicitly if this is the case.

Note: there are formats that use fixed encoding (like most binary data formats) and that ignore passed in encoding.

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Parameters:
out OutputStream to use for writing JSON content
enc Character encoding to use
Since:
2.1 Will eventually replace createJsonGenerator variant.
 
         throws IOException
     {
         return createJsonGenerator(outenc);
     }

    
Method for constructing JSON generator for writing JSON content using specified Writer.

Underlying stream is NOT owned by the generator constructed, so that generator will NOT close the Reader when JsonGenerator.close() is called (unless auto-closing feature, JsonGenerator.Feature.AUTO_CLOSE_TARGET is enabled). Using application needs to close it explicitly.

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Parameters:
out Writer to use for writing JSON content
Since:
2.1 Will eventually replace createJsonGenerator variant.
 
     public JsonGenerator createGenerator(Writer out)
         throws IOException
     {
         return createJsonGenerator(out);
     }

    
Convenience method for constructing generator that uses default encoding of the format (UTF-8 for JSON and most other data formats).

Note: there are formats that use fixed encoding (like most binary data formats).

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Since:
2.1 Will eventually replace createJsonGenerator variant.
 
     public JsonGenerator createGenerator(OutputStream outthrows IOException {
        return createJsonGenerator(out);
    }
    
    
Method for constructing JSON generator for writing JSON content to specified file, overwriting contents it might have (or creating it if such file does not yet exist). Encoding to use must be specified, and needs to be one of available types (as per JSON specification).

Underlying stream is owned by the generator constructed, i.e. generator will handle closing of file when JsonGenerator.close() is called.

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Parameters:
f File to write contents to
enc Character encoding to use
Since:
2.1 Will eventually replace createJsonGenerator variant.
        throws IOException
    {
        return createJsonGenerator(fenc);
    }    
    /*
    /**********************************************************
    /* Generator factories, old (as per [Issue-25]
    /**********************************************************
     */

    
Method for constructing JSON generator for writing JSON content using specified output stream. Encoding to use must be specified, and needs to be one of available types (as per JSON specification).

Underlying stream is NOT owned by the generator constructed, so that generator will NOT close the output stream when JsonGenerator.close() is called (unless auto-closing feature, JsonGenerator.Feature.AUTO_CLOSE_TARGET is enabled). Using application needs to close it explicitly if this is the case.

Note: there are formats that use fixed encoding (like most binary data formats) and that ignore passed in encoding.

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Parameters:
out OutputStream to use for writing JSON content
enc Character encoding to use
        throws IOException
    {
	// false -> we won't manage the stream unless explicitly directed to
        IOContext ctxt = _createContext(outfalse);
        ctxt.setEncoding(enc);
        if (enc == .) {
            // [JACKSON-512]: allow wrapping with _outputDecorator
            if ( != null) {
                out = .decorate(ctxtout);
            }
            return _createUTF8JsonGenerator(outctxt);
        }
        Writer w = _createWriter(outencctxt);
        // [JACKSON-512]: allow wrapping with _outputDecorator
        if ( != null) {
            w = .decorate(ctxtw);
        }
	return _createGenerator(wctxt);
    }

    
Method for constructing JSON generator for writing JSON content using specified Writer.

Underlying stream is NOT owned by the generator constructed, so that generator will NOT close the Reader when JsonGenerator.close() is called (unless auto-closing feature, JsonGenerator.Feature.AUTO_CLOSE_TARGET is enabled). Using application needs to close it explicitly.

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Parameters:
out Writer to use for writing JSON content
        throws IOException
    {
        IOContext ctxt = _createContext(outfalse);
        // [JACKSON-512]: allow wrapping with _outputDecorator
        if ( != null) {
            out = .decorate(ctxtout);
        }
	return _createGenerator(outctxt);
    }

    
Convenience method for constructing generator that uses default encoding of the format (UTF-8 for JSON and most other data formats).

Note: there are formats that use fixed encoding (like most binary data formats).

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

        return createJsonGenerator(out.);
    }
    
    
Method for constructing JSON generator for writing JSON content to specified file, overwriting contents it might have (or creating it if such file does not yet exist). Encoding to use must be specified, and needs to be one of available types (as per JSON specification).

Underlying stream is owned by the generator constructed, i.e. generator will handle closing of file when JsonGenerator.close() is called.

NOTE: starting with 2.1, should not be used (will be deprecated in 2.2); instead, should call createGenerator.

Parameters:
f File to write contents to
enc Character encoding to use
        throws IOException
    {
	// true -> yes, we have to manage the stream since we created it
        IOContext ctxt = _createContext(outtrue);
        ctxt.setEncoding(enc);
        if (enc == .) {
            // [JACKSON-512]: allow wrapping with _outputDecorator
            if ( != null) {
                out = .decorate(ctxtout);
            }
            return _createUTF8JsonGenerator(outctxt);
        }
        Writer w = _createWriter(outencctxt);
        // [JACKSON-512]: allow wrapping with _outputDecorator
        if ( != null) {
            w = .decorate(ctxtw);
        }
	return _createGenerator(wctxt);
    }
    /*
    /**********************************************************
    /* Factory methods used by factory for creating parser instances,
    /* overridable by sub-classes
    /**********************************************************
     */

    
Overridable factory method that actually instantiates desired parser given java.io.InputStream and context object.

This method is specifically designed to remain compatible between minor versions so that sub-classes can count on it being called as expected. That is, it is part of official interface from sub-class perspective, although not a public method available to users of factory implementations.

Since:
2.1
    protected JsonParser _createParser(InputStream inIOContext ctxt)
        throws IOExceptionJsonParseException
    {
        /* NOTE: MUST call the deprecated method until it is deleted, just so
         * that override still works as expected, for now.
         */
        return _createJsonParser(inctxt);
    }

    
        // As per [JACKSON-259], may want to fully disable canonicalization:
        return new ByteSourceJsonBootstrapper(ctxtin).constructParser(,
                ,
                isEnabled(..),
                isEnabled(..));
    }
    
    
Overridable factory method that actually instantiates parser using given java.io.Reader object for reading content.

This method is specifically designed to remain compatible between minor versions so that sub-classes can count on it being called as expected. That is, it is part of official interface from sub-class perspective, although not a public method available to users of factory implementations.

Since:
2.1
    protected JsonParser _createParser(Reader rIOContext ctxt)
        throws IOExceptionJsonParseException
    {
        /* NOTE: MUST call the deprecated method until it is deleted, just so
         * that override still works as expected, for now.
         */
        return _createJsonParser(rctxt);
    }

    
    protected JsonParser _createJsonParser(Reader rIOContext ctxtthrows IOExceptionJsonParseException {
        return new ReaderBasedJsonParser(ctxtr,
                    isEnabled(..)));
    }

    
Overridable factory method that actually instantiates parser using given java.io.Reader object for reading content passed as raw byte array.

This method is specifically designed to remain compatible between minor versions so that sub-classes can count on it being called as expected. That is, it is part of official interface from sub-class perspective, although not a public method available to users of factory implementations.

    protected JsonParser _createParser(byte[] dataint offsetint lenIOContext ctxt)
        throws IOExceptionJsonParseException
    {
        /* NOTE: MUST call the deprecated method until it is deleted, just so
         * that override still works as expected, for now.
         */
        return _createJsonParser(dataoffsetlenctxt);
    }

    
    protected JsonParser _createJsonParser(byte[] dataint offsetint lenIOContext ctxtthrows IOExceptionJsonParseException {
        return new ByteSourceJsonBootstrapper(ctxtdataoffsetlen).constructParser(,
                ,
                isEnabled(..),
                isEnabled(..));
    }
    
    /*
    /**********************************************************
    /* Factory methods used by factory for creating generator instances,
    /* overridable by sub-classes
    /**********************************************************
     */
    
    
Overridable factory method that actually instantiates generator for given java.io.Writer and context object.

This method is specifically designed to remain compatible between minor versions so that sub-classes can count on it being called as expected. That is, it is part of official interface from sub-class perspective, although not a public method available to users of factory implementations.

    protected JsonGenerator _createGenerator(Writer outIOContext ctxt)
        throws IOException
    {
        /* NOTE: MUST call the deprecated method until it is deleted, just so
         * that override still works as expected, for now.
         */
        return _createJsonGenerator(outctxt);
    }

    
    protected JsonGenerator _createJsonGenerator(Writer outIOContext ctxt)
        throws IOException
    {
        WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt,
                out);
        if ( != null) {
            gen.setCharacterEscapes();
        }
        SerializableString rootSep = ;
        if (rootSep != ) {
            gen.setRootValueSeparator(rootSep);
        }
        return gen;
    }

    
Overridable factory method that actually instantiates generator for given java.io.OutputStream and context object, using UTF-8 encoding.

This method is specifically designed to remain compatible between minor versions so that sub-classes can count on it being called as expected. That is, it is part of official interface from sub-class perspective, although not a public method available to users of factory implementations.

    protected JsonGenerator _createUTF8Generator(OutputStream outIOContext ctxtthrows IOException {
        return _createUTF8JsonGenerator(outctxt);
    }

    

Deprecated:
since 2.1
        throws IOException
    {
        UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt,
                out);
        if ( != null) {
            gen.setCharacterEscapes();
        }
        SerializableString rootSep = ;
        if (rootSep != ) {
            gen.setRootValueSeparator(rootSep);
        }
        return gen;
    }
    protected Writer _createWriter(OutputStream outJsonEncoding encIOContext ctxtthrows IOException
    {
        // note: this should not get called any more (caller checks, dispatches)
        if (enc == .) { // We have optimized writer for UTF-8
            return new UTF8Writer(ctxtout);
        }
        // not optimal, but should do unless we really care about UTF-16/32 encoding speed
        return new OutputStreamWriter(outenc.getJavaName());
    }
    
    /*
    /**********************************************************
    /* Internal factory methods, other
    /**********************************************************
     */

    
Overridable factory method that actually instantiates desired context object.
    protected IOContext _createContext(Object srcRefboolean resourceManaged)
    {
        return new IOContext(_getBufferRecycler(), srcRefresourceManaged);
    }

    
Method used by factory to create buffer recycler instances for parsers and generators.

Note: only public to give access for ObjectMapper

    {
        SoftReference<BufferRecyclerref = .get();
        BufferRecycler br = (ref == null) ? null : ref.get();
        if (br == null) {
            br = new BufferRecycler();
            .set(new SoftReference<BufferRecycler>(br));
        }
        return br;
    }
    
    
Helper methods used for constructing an optimal stream for parsers to use, when input is to be read from an URL. This helps when reading file content via URL.
    protected InputStream _optimizedStreamFromURL(URL url)
        throws IOException
    {
        if ("file".equals(url.getProtocol())) {
            /* Can not do this if the path refers
             * to a network drive on windows. This fixes the problem;
             * might not be needed on all platforms (NFS?), but should not
             * matter a lot: performance penalty of extra wrapping is more
             * relevant when accessing local file system.
             */
            String host = url.getHost();
            if (host == null || host.length() == 0) {
                 // [Issue#48]: Let's try to avoid probs with URL encoded stuff
                 String path = url.getPath();
                 if (path.indexOf('%') < 0) {
                     return new FileInputStream(url.getPath());
                 }
                 // otherwise, let's fall through and let URL decoder do its magic
                 return new FileInputStream(url.getPath());
            }
        }
        return url.openStream();
    }
New to GrepCode? Check out our FAQ X