zoukankan      html  css  js  c++  java
  • Gson and Json

    摘自https://blog.csdn.net/liyuanjinglyj/article/details/45890825

    1.JSON

    JSON是JavaScript Object Notation的缩写,是JavaScript标准的一个子集。官方Android API已经内置支持读写JSON数据。这种格式非常适合表示不包含二进制数据的复杂对象。从某种程度上说,它也成了网络上共享数据的事实标准。

    下面的例子显示了一个简单的JSON数组,它包含3个对象,每个对象都存储People的信息。这种格式非常适合在网络服务上发送任务或者直接在朋友中共享数据。

    [

    {

    "name":"liyuanjinglyj",

    "age":"22",

    "lon":"12"

    },

    {

    "name":"fengxinyao",

    "age":"24",

    "lon":"22"

    },

    {

    "name":"hefan",

    "age":"23",

    "lon":"11"

    }

    ]

    从InputStream读取JSON数据最好使用JsonReader API,如下所示:

    public JSONArray readPeopleFromInputStream(InputStream inputStream){
        InputStreamReader reader=new InputStreamReader(inputStream);
        JsonReader jsonReader=new JsonReader(reader);
        JSONArray jsonArray=new JSONArray();
        try {
            jsonReader.beginArray();
            while(jsonReader.hasNext()){
                JSONObject jsonObject=readSingleJSON(jsonReader);
                jsonArray.put(jsonObject);
            }
            jsonReader.endArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }
    
    private JSONObject readSingleJSON(JsonReader jsonReader)throws Exception{
        JSONObject jsonObject=new JSONObject();
        jsonReader.beginObject();
        JsonToken token;
        do{
            String name=jsonReader.nextName();
            if("name".equals(name)){
                jsonObject.put("name",jsonReader.nextString());
            }else if("age".equals(name)){
                jsonObject.put("age",jsonReader.nextString());
            }else if("lon".equals(name)){
                jsonObject.put("lon",jsonReader.nextString());
            }
            token=jsonReader.peek();
        }while(token!=null&&!token.equals(JsonToken.END_OBJECT));
        jsonReader.endObject();
        return jsonObject;
    }
        虽然也可以把InputStream中的全部内容都读到String中,然后传给JSONArray的构造函数,但前面的方法消耗内存少,并且很可能很快。同样,JsonWriter类允许OutputStream高效地写入JSON数据,如下所示:
    
    
    public void writePeopleJSON(JSONArray jsonArray,OutputStream outputStream) throws Exception {
        OutputStreamWriter write=new OutputStreamWriter(outputStream);
        JsonWriter jsonWrite=new JsonWriter(write);
        int arrayLength=jsonArray.length();
        jsonWrite.beginArray();
        for (int i = 0; i < arrayLength; i++) {
            JSONObject jsonObject= (JSONObject) jsonArray.get(i);
            jsonWrite.beginObject();
            jsonWrite.name("name").value(jsonObject.getString("name"));
            jsonWrite.name("age").value(jsonObject.getString("age"));
            jsonWrite.name("lon").value(jsonObject.getString("lon"));
            jsonWrite.endObject();
        }
        jsonWrite.endArray();
        jsonWrite.close();
    }
        

    2.使用Gson进行高级JSON处理

        JSONObject和JSONArray类使用起来很方便,但它们有一定的局限性,并且通常会消耗更多不必要的内存。同样,如果有多个不同类型的对象,使用JsonReader和JsonWriteer需要编写相当多的代码。如果为更高级的JSON数据序列化和反序列化方法,可以使用优秀的开源库Gson。
        Gson允许把简单的Java对象(Plain Old Object,POJO)转换成JSON,反之亦然。开发者所要做的就是把数据定义成普通的Java对象,提供get和set方法,并在项目中引入Gson库。
        下面的类显示了一个表示任务的简单Java对象:
    
    
    public class People {
        private String name;
        private String age;
        private String lon;
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public void setLon(String lon) {
            this.lon = lon;
        }
    
        public String getName() {
            return name;
        }
    
        public String getAge() {
            return age;
        }
    
        public String getLon() {
            return lon;
        }
    }
    

    下面的代码显示如何读取和写入Collection<People>对象集合。序列化形式始终是有效的JSON数据,因此向Web服务发布JSON格式的数据时选择它会很方便。如果开发者也负责服务器端的代码,并且恰好使用Java语言,那么就可以在服务器端和Android应用间轻松的共享同一组Java代码。

    
    
    public Collection<People> readPeopleFromStream(InputStream inputStream){
        InputStreamReader reader=new InputStreamReader(inputStream);
        Gson gson=new Gson();
        Type type=new TypeToken<Collection<People>>(){}.getType();
        return gson.fromJson(reader,type);
    }
    
    public void writePeopleToStream(Collection<People> peoples,OutputStream outputStream) throws IOException {
        OutputStreamWriter write=new OutputStreamWriter(outputStream,"UTF-8");
        com.google.gson.stream.JsonWriter jsonWrite= new com.google.gson.stream.JsonWriter(write);
        Gson gson=new Gson();
        Type type=new TypeToken<Collection<People>>(){}.getType();
        gson.toJson(peoples,type,jsonWrite);
        Log.i("MainActivity", "GSON");
        jsonWrite.flush();
        jsonWrite.close();
    }
  • 相关阅读:
    HDU 6430 Problem E. TeaTree(虚树)
    hdu6437 Problem L.Videos(网络流)
    Rikka with Prefix Sum(组合数学)
    借教室
    2018年全国多校算法寒假训练营练习比赛(第五场)H Tree Recovery
    1296 营业额统计
    FZU oj Problem 2082 过路费
    大数乘法(适合k进制)
    重载小于号
    莫比乌斯
  • 原文地址:https://www.cnblogs.com/yfafa/p/9064684.html
Copyright © 2011-2022 走看看