你不知道的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开发包

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/liyuanjinglyj/p/4656568.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值