zoukankan      html  css  js  c++  java
  • 利用JsonReade和JsonReader实现json解析和写数据

      前面讲过调用谷歌的json包来对json数据进行解析,随着android的发展现在手机系统都是android4.0以上版本了,因此可以直接调用sdk 中的JsonReader来解析json数据了。json数据的解析成现有的类,这些类通常是javaBean类,通过查看官方的文档将其文档的例子完善了下如下:

    json数据:

    [
       {
         "id": 912345678901,
         "text": "How do I read JSON on Android?",
         "geo": null,
         "user": 
    	{
           "name": "android_newb",
           "followers_count": 41
         	 }
        },
       {
         "id": 912345678902,
         "text": "@android_newb just use android.util.JsonReader!",
         "geo": [50.454722, -104.606667],
         "user": 
    	{
           "name": "jesse",
           "followers_count": 2
         	}
        }
     ]

    需要解析出来的类:

    package com.example.user.myjosn;
    
    import java.util.List;
    
    /**
     * Created by user on 2016/10/18.
     */
    public class MyMessage {
    
        long  id;
        String text;
        List geo;
        User user;
        public MyMessage(long id,String text, User user, List geo)
        {
            this.id= id;
            this.user= user;
            this.geo = geo;
            this.text = text;
        }
    
    }
    class  User
    {
        public  User(String name,int count)
        {
            this.name= name;
            this.followers_count = count;
        }
        String name;
        int followers_count;
    }
    

     解析json的类:调用readJsonStream函数就可以解析出该json文件,该解析和xml解析相似,开头分reader.beginArray 和reader.beginObject 第一个是接下来解析一个数组,通常里面嵌套解析一个解析另外个对象的函数,后面一个就是解析对象,然后就是相应的end结束语句,且对象里面含有对象,因此对象的读取是嵌套实现的:

    package com.example.user.myjosn;
    
    import android.os.Message;
    import android.util.JsonReader;
    import android.util.JsonToken;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by user on 2016/10/18.
     */
    public class MyMessageJsonReader {
    /*
        in 为要读取的文件的输入流
     */
        public  List readJsonStream(InputStream in) throws IOException {
            JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
            try {
                return readMessagesArray(reader);
            }
                finally{
                    reader.close();
                }
            }
    
    
        public List readMessagesArray(JsonReader reader) throws IOException {
            List messages = new ArrayList();
    
            reader.beginArray();
            while (reader.hasNext()) {
                messages.add(readMessage(reader));
            }
            reader.endArray();
            return messages;
        }
    
        public MyMessage readMessage(JsonReader reader) throws IOException {
            long id = -1;
            String text = null;
            User user = null;
            List geo = null;
    
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if (name.equals("id")) {
                    id = reader.nextLong();
                } else if (name.equals("text")) {
                    text = reader.nextString();
                } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {//后面一个判断geo的值不为空,因为有可能为空
                    geo = readDoublesArray(reader);
                } else if (name.equals("user")) {
                    user = readUser(reader);
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
            return new MyMessage(id, text, user, geo);
        }
    
        //读取double型的数组,主要是读取geo项的数组
        public List readDoublesArray(JsonReader reader) throws IOException {
            List doubles = new ArrayList();
    
            reader.beginArray();
            while (reader.hasNext()) {
                doubles.add(reader.nextDouble());
            }
            reader.endArray();
            return doubles;
        }
    
        public User readUser(JsonReader reader) throws IOException {
            String username = null;
            int followersCount = -1;
    
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if (name.equals("name")) {
                    username = reader.nextString();
                } else if (name.equals("followers_count")) {
                    followersCount = reader.nextInt();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
            return new User(username, followersCount);
        }
    
    
    }
    

      解析完了后得到了list对象,存储的是MyMessage对象,下面我们利用JsonWriter来自己写json数据:写的内容就是上面的得到的list里面的MyMessage对象,写的内容和读的一模一样:下面给出写的类:

    package com.example.user.myjosn;
    
    import android.util.JsonWriter;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.util.List;
    
    /**
     * Created by user on 2016/10/18.
     */
    public class MyMessageJsonWriter {
    
        public  void writeJsonStream(OutputStream out, List messages) throws IOException {
            JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.setIndent("  ");
            writeMessagesArray(writer, messages);
            writer.close();
        }
    
    
        public void writeMessagesArray(JsonWriter writer, List messages) throws IOException {
            writer.beginArray();
            for (Object message : messages) {
                writeMessage(writer,(MyMessage) message);
            }
            writer.endArray();
        }
    
        public void writeMessage(JsonWriter writer, MyMessage 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.getFollowers_count());
            writer.endObject();
        }
    
        public void writeDoublesArray(JsonWriter writer, List doubles) throws IOException {
            writer.beginArray();
            for (Object value : doubles) {
                writer.value((Double)value);
            }
            writer.endArray();
        }
    
    }
    

      主函数Activity:

    package com.example.user.myjosn;
    
    import android.content.Context;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        ArrayList<MyMessage> list;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //读取data目录下的json数据存储到集合中
            try {
               InputStream in = new FileInputStream( "data/data/com.example.user.myjosn/files/jsondemo.txt");
                MyMessageJsonReader mJson = new MyMessageJsonReader();
                list = (ArrayList<MyMessage>) mJson.readJsonStream(in);
                System.out.println("第一个"+list.get(0).id);
    
            } catch (FileNotFoundException e) {
                System.out.println("文件没找到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("读取文件失败");
                e.printStackTrace();
            }
    
            //将上面得到的MyMessage对象的数据写入成json数据
            try {
                OutputStream outputStream =  openFileOutput("message", Context.MODE_PRIVATE);
                MyMessageJsonWriter myMessageJsonWriter = new MyMessageJsonWriter();
                myMessageJsonWriter.writeJsonStream(outputStream, list);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    

      

      

     

  • 相关阅读:
    Linux查看当前系统的发行版信息
    用 CentOS 7 打造合适的科研环境
    消息队列的使用场景
    RabbitMQ几种Exchange 模式
    JMS规范概览
    消息队列的学习
    springMVC参数传递实例
    java8时间处理实例
    windows电脑常用必备软件
    http后台json解析实例
  • 原文地址:https://www.cnblogs.com/bokeofzp/p/5973667.html
Copyright © 2011-2022 走看看