com.google.gson.stream
Class JsonWriter

java.lang.Object
  extended by com.google.gson.stream.JsonWriter
All Implemented Interfaces:
Closeable

public final class JsonWriter
extends Object
implements Closeable

Writes a JSON (RFC 4627) encoded value to a stream, one token at a time. The stream includes both literal values (strings, numbers, booleans and nulls) as well as the begin and end delimiters of objects and arrays.

Encoding JSON

To encode your data as JSON, create a new JsonWriter. Each JSON document must contain one top-level array or object. Call methods on the writer as you walk the structure's contents, nesting arrays and objects as necessary:

Example

Suppose we'd like to encode a stream of messages such as the following:
 [
   {
     "id": 912345678901,
     "text": "How do I stream JSON in Java?",
     "geo": null,
     "user": {
       "name": "json_newb",
       "followers_count": 41
      }
   },
   {
     "id": 912345678902,
     "text": "@json_newb just use JsonWriter!",
     "geo": [50.454722, -104.606667],
     "user": {
       "name": "jesse",
       "followers_count": 2
     }
   }
 ]
This code encodes the above structure:
   public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {
     JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
     writer.setIndentSpaces(4);
     writeMessagesArray(writer, messages);
     writer.close();
   }

   public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {
     writer.beginArray();
     for (Message message : messages) {
       writeMessage(writer, message);
     }
     writer.endArray();
   }

   public void writeMessage(JsonWriter writer, Message message) throws IOException {
     writer.beginObject();
     writer.name("id").value(message.getId());
     writer.name("text").value(message.getText());
     if (message.getGeo() != null) {
       writer.name("geo");
       writeDoublesArray(writer, message.getGeo());
     } else {
       writer.name("geo").nullValue();
     }
     writer.name("user");
     writeUser(writer, message.getUser());
     writer.endObject();
   }

   public void writeUser(JsonWriter writer, User user) throws IOException {
     writer.beginObject();
     writer.name("name").value(user.getName());
     writer.name("followers_count").value(user.getFollowersCount());
     writer.endObject();
   }

   public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {
     writer.beginArray();
     for (Double value : doubles) {
       writer.value(value);
     }
     writer.endArray();
   }

Each JsonWriter may be used to write a single JSON stream. Instances of this class are not thread safe. Calls that would result in a malformed JSON string will fail with an IllegalStateException.

Since:
1.6
Author:
Jesse Wilson

Constructor Summary
JsonWriter(Writer out)
          Creates a new instance that writes a JSON-encoded stream to out.
 
Method Summary
 JsonWriter beginArray()
          Begins encoding a new array.
 JsonWriter beginObject()
          Begins encoding a new object.
 void close()
          Flushes and closes this writer and the underlying Writer.
 JsonWriter endArray()
          Ends encoding the current array.
 JsonWriter endObject()
          Ends encoding the current object.
 void flush()
          Ensures all buffered data is written to the underlying Writer and flushes that writer.
 boolean isHtmlSafe()
          Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.
 boolean isLenient()
          Returns true if this writer has relaxed syntax rules.
 JsonWriter name(String name)
          Encodes the property name.
 JsonWriter nullValue()
          Encodes null.
 void setHtmlSafe(boolean htmlSafe)
          Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.
 void setIndent(String indent)
          Sets the indentation string to be repeated for each level of indentation in the encoded document.
 void setLenient(boolean lenient)
          Configure this writer to relax its syntax rules.
 JsonWriter value(boolean value)
          Encodes value.
 JsonWriter value(double value)
          Encodes value.
 JsonWriter value(JsonLiteral value)
          Writes value literally
 JsonWriter value(long value)
          Encodes value.
 JsonWriter value(Number value)
          Encodes value.
 JsonWriter value(String value)
          Encodes value.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

JsonWriter

public JsonWriter(Writer out)
Creates a new instance that writes a JSON-encoded stream to out. For best performance, ensure Writer is buffered; wrapping in BufferedWriter if necessary.

Method Detail

setIndent

public void setIndent(String indent)
Sets the indentation string to be repeated for each level of indentation in the encoded document. If indent.isEmpty() the encoded document will be compact. Otherwise the encoded document will be more human-readable.

Parameters:
indent - a string containing only whitespace.

setLenient

public void setLenient(boolean lenient)
Configure this writer to relax its syntax rules. By default, this writer only emits well-formed JSON as specified by RFC 4627. Setting the writer to lenient permits the following:


isLenient

public boolean isLenient()
Returns true if this writer has relaxed syntax rules.


setHtmlSafe

public void setHtmlSafe(boolean htmlSafe)
Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents. This escapes the HTML characters <, >, & and = before writing them to the stream. Without this setting, your XML/HTML encoder should replace these characters with the corresponding escape sequences.


isHtmlSafe

public boolean isHtmlSafe()
Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.


beginArray

public JsonWriter beginArray()
                      throws IOException
Begins encoding a new array. Each call to this method must be paired with a call to endArray().

Returns:
this writer.
Throws:
IOException

endArray

public JsonWriter endArray()
                    throws IOException
Ends encoding the current array.

Returns:
this writer.
Throws:
IOException

beginObject

public JsonWriter beginObject()
                       throws IOException
Begins encoding a new object. Each call to this method must be paired with a call to endObject().

Returns:
this writer.
Throws:
IOException

endObject

public JsonWriter endObject()
                     throws IOException
Ends encoding the current object.

Returns:
this writer.
Throws:
IOException

name

public JsonWriter name(String name)
                throws IOException
Encodes the property name.

Parameters:
name - the name of the forthcoming value. May not be null.
Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(String value)
                 throws IOException
Encodes value.

Parameters:
value - the literal string value, or null to encode a null literal.
Returns:
this writer.
Throws:
IOException

nullValue

public JsonWriter nullValue()
                     throws IOException
Encodes null.

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(JsonLiteral value)
                 throws IOException
Writes value literally

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(boolean value)
                 throws IOException
Encodes value.

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(double value)
                 throws IOException
Encodes value.

Parameters:
value - a finite value. May not be NaNs or infinities.
Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(long value)
                 throws IOException
Encodes value.

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(Number value)
                 throws IOException
Encodes value.

Parameters:
value - a finite value. May not be NaNs or infinities.
Returns:
this writer.
Throws:
IOException

flush

public void flush()
           throws IOException
Ensures all buffered data is written to the underlying Writer and flushes that writer.

Throws:
IOException

close

public void close()
           throws IOException
Flushes and closes this writer and the underlying Writer.

Specified by:
close in interface Closeable
Throws:
IOException - if the JSON document is incomplete.


Copyright © 2009-2011 jclouds. All Rights Reserved.