Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Gson、Fastjson 與原生 API:Android 端 JSON 解析效能實測比較

編輯:關於 Android 程式設計

iOS 系統內建的 JSON 解析速度本來就很快,這裡不談。今天要比的是 Android 上幾個常見的解析方案:系統自帶的 org.json、Google 的 Gson,以及阿里巴巴開源的 Fastjson。

Gson 的用法

Gson 上手極為簡單,把 JSON 字串與對應的 Bean 型別交給 fromJson 即可:

Gson gson = new Gson();
List<StatusObject> so = gson.fromJson(mJsonString,
        new TypeToken<List<StatusObject>>() { }.getType());

這裡有個前提:Bean 類別中的欄位名稱必須和 JSON 中的鍵完全一致,並且提供 get/set 方法(原因後面會說明)。標準的 Bean 長這樣:

import java.util.List;

public class Geo {
    private String type;
    private List<Float> coordinates;

    public Geo() {}

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<Float> getCoordinates() {
        return coordinates;
    }

    public void setCoordinates(List<Float> coordinates) {
        this.coordinates = coordinates;
    }
}

我曾經擔心巢狀結構會解析失敗,實測之後發現就算 Bean 裡再嵌其他 Bean,一樣能層層迭代賦值。

Fastjson 的用法與 Gson 幾乎一致,差別在底層實作,這裡不展開。

效能對比

用 25 筆結構相當複雜的 JSON 資料做測試,結果如下:

Gson 在這個測試中有明顯的優勢。往下看它的實作或許能找到原因。

深入原始碼:快在哪裡

關鍵類別是 JsonObject.java:

package com.google.gson;

import com.google.gson.internal.LinkedTreeMap;
import java.util.Map.Entry;
import java.util.Set;

public final class JsonObject extends JsonElement {
    private final LinkedTreeMap<String, JsonElement> members = new LinkedTreeMap<String, JsonElement>();

    JsonObject deepCopy() {
        JsonObject result = new JsonObject();
        for (Map.Entry<String, JsonElement> entry : this.members.entrySet()) {
            result.add(entry.getKey(), entry.getValue().deepCopy());
        }
        return result;
    }

    public void add(String property, JsonElement value) {
        if (value == null) {
            value = JsonNull.INSTANCE;
        }
        this.members.put(property, value);
    }

    public JsonElement remove(String property) {
        return this.members.remove(property);
    }

    public void addProperty(String property, String value) {
        add(property, createJsonElement(value));
    }

    public void addProperty(String property, Number value) {
        add(property, createJsonElement(value));
    }

    public void addProperty(String property, Boolean value) {
        add(property, createJsonElement(value));
    }

    public void addProperty(String property, Character value) {
        add(property, createJsonElement(value));
    }

    private JsonElement createJsonElement(Object value) {
        return value == null ? JsonNull.INSTANCE : new JsonPrimitive(value);
    }

    public Set<Map.Entry<String, JsonElement>> entrySet() {
        return this.members.entrySet();
    }

    public boolean has(String memberName) {
        return this.members.containsKey(memberName);
    }

    public JsonElement get(String memberName) {
        return this.members.get(memberName);
    }

    public JsonPrimitive getAsJsonPrimitive(String memberName) {
        return (JsonPrimitive) this.members.get(memberName);
    }

    public JsonArray getAsJsonArray(String memberName) {
        return (JsonArray) this.members.get(memberName);
    }

    public JsonObject getAsJsonObject(String memberName) {
        return (JsonObject) this.members.get(memberName);
    }

    public boolean equals(Object o) {
        return (o == this) || ((o instanceof JsonObject)
                && ((JsonObject) o).members.equals(this.members));
    }

    public int hashCode() {
        return this.members.hashCode();
    }
}

可以看到它用 LinkedTreeMap 快取值屬性與對應元素。這種以鍵值對形式維護的結構,查找時不必像逐欄位比對那樣來回掃描,自然比直接呼叫原生 API 找節點要快。

接著看賦值環節,在 ProtoTypeAdapter.java 中找到反序列化的實作:

@SuppressWarnings("unchecked")
@Override
public GeneratedMessage deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    try {
        JsonObject jsonObject = json.getAsJsonObject();
        Class<? extends GeneratedMessage> protoClass =
                (Class<? extends GeneratedMessage>) typeOfT;
        try {
            // 呼叫 ProtoClass.newBuilder()
            Object protoBuilder = getCachedMethod(protoClass, "newBuilder").invoke(null);
            Class<?> builderClass = protoBuilder.getClass();
            Descriptor protoDescriptor = (Descriptor) getCachedMethod(
                    protoClass, "getDescriptor").invoke(null);

            // 對所有可用欄位呼叫 setter
            for (FieldDescriptor fieldDescriptor : protoDescriptor.getFields()) {
                String name = fieldDescriptor.getName();
                if (jsonObject.has(name)) {
                    JsonElement jsonElement = jsonObject.get(name);
                    String fieldName = name + "_";
                    Field field = protoClass.getDeclaredField(fieldName);
                    Type fieldType = field.getGenericType();
                    Object fieldValue = context.deserialize(jsonElement, fieldType);
                    Method method = getCachedMethod(builderClass, "setField",
                            FieldDescriptor.class, Object.class);
                    method.invoke(protoBuilder, fieldDescriptor, fieldValue);
                }
            }

            // 呼叫 build 取得最終物件
            return (GeneratedMessage) getCachedMethod(builderClass, "build").invoke(protoBuilder);
        } catch (SecurityException e) {
            throw new JsonParseException(e);
        } catch (NoSuchMethodException e) {
            throw new JsonParseException(e);
        } catch (IllegalArgumentException e) {
            throw new JsonParseException(e);
        } catch (IllegalAccessException e) {
            throw new JsonParseException(e);
        } catch (InvocationTargetException e) {
            throw new JsonParseException(e);
        }
    } catch (Exception e) {
        throw new JsonParseException("Error while parsing proto: ", e);
    }
}

這裡透過反射呼叫 setter 來為變數賦值——這也正好解釋了為什麼前面強調 Bean 一定要寫 get/set 方法:沒有 setter,反射就無從下手。

選型建議

單純從這組測試看,Gson 表現最好;不過實務上還要權衡其他因素:是否只想依賴系統 API 而不引入第三方套件、是否需要處理極端巢狀或超大 JSON、以及團隊對各套件的熟悉度。效能只是其中一項,維護性與可讀性同樣重要。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved