Академический Документы
Профессиональный Документы
Культура Документы
java.lang.Object
↳ android.util.JsonWriter
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:
● To write arrays, first call beginArray(). Write each of the array's elements with the
appropriate value(boolean) methods or by nesting other arrays and objects. Finally close
the array using e
ndArray().
● To write objects, first call beginObject(). Write each of the object's properties by
alternating calls to n
ame(String) with the property's value. Write property values with the
appropriate value(boolean) method or by nesting other objects or arrays. Finally close
the object using endObject().
Example
Suppose we'd like to encode a stream of messages such as the following:
[
{
"id": 912345678901,
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
},
{
"id": 912345678902,
"user": {
"name": "jesse",
"followers_count": 2
}
}
]
This code encodes the above structure:
public void writeJsonStream(OutputStream out, List<Message> messages) throws
IOException {
writer.setIndent(" ");
writeMessagesArray(writer, messages);
writer.close();
}
writer.beginArray();
writeMessage(writer, message);
}
writer.endArray();
}
writer.beginObject();
writer.name("id").value(message.g
etId());
writer.name("text").value(message.getText());
writer.name("geo");
writeDoublesArray(writer, message.getGeo());
} else {
writer.name("geo").nullValue();
}
writer.name("user");
writeUser(writer, message.getUser());
writer.endObject();
}
writer.beginObject();
writer.name("name").value(user.g
etName());
writer.name("followers_count").value(user.getFollowersCount());
writer.endObject();
}
writer.beginArray();
writer.value(value);
}
writer.endArray();
}
Each J sonWriter 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.
Summary
Public constructors
JsonWriter(Writer out)