JsonWriter使用

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();
 
}

JsonWriter使用,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。