你不知道的JSON的高效率用法,json高效率用法

來源:互聯網
上載者:User

你不知道的JSON的高效率用法,json高效率用法

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();}
本文還提供了最新的GSON包供各位程式員朋友們下載,請查看附件。GSON開發包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.