zoukankan      html  css  js  c++  java
  • 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();
     
    }
  • 相关阅读:
    元素查找
    合并果子 2004年NOIP全国联赛普及组
    队列练习1,2,3
    山峰
    栈练习1,2,3
    天使之城
    括号序列
    布尔表达式
    逆波兰表达式
    旅行家的预算 1999年NOIP全国联赛普及组NOIP全国联赛提高组
  • 原文地址:https://www.cnblogs.com/bravestarrhu/p/3605623.html
Copyright © 2011-2022 走看看