Example:
拼一个如下的json格式String
{
[
{
"id": 912345678901,
"text": "How do I write JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
},
{
"id": 912345678902,
"text": "@android_newb just use android.util.JsonWriter!",
"geo": [
50.454722,
-104.606667
],
"user": {
"name": "jesse",
"followers_count": 2
}
}
]
}
关键代码:
public static String writeJsonStream(List<Message> messages)throwsIOException{
if(messages!=null &&
messages
.size() > 0){
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
writer.setIndent("");
writeMessagesArray(writer, messages);
writer.close();
byte[] bytes = out.toByteArray();
return new String(bytes)
;
}
return null;
}
private static void writeMessagesArray(JsonWriter writer,List messages)throwsIOException{
writer.beginArray();
for(Message message : messages){
writeMessage(writer, message);
}
writer.endArray();
}
private static void writeMessage(JsonWriter writer,Message message)throwsIOException{
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();
}
private static void writeUser(JsonWriter writer,User user)throwsIOException{
writer.beginObject();
writer.name("name").value(user.getName());
writer.name("followers_count").value(user.getFollowersCount());
writer.endObject();
}
private static void writeDoublesArray(JsonWriter writer,List doubles)throwsIOException{
writer.beginArray();
for(Double value : doubles){
writer.value(value);
}
writer.endArray();
}