Android Json應用

1. Json簡介

Json是一種輕量級文本數據交換格式,類似於XML,但比XML更小、更快、更易解析。
Json用於描述數據結構有兩個方式

  • 名稱/值(JSONObject)
  • 值的有序列表(JSONArray)

2. 原生Json

(1) JSONObject表示json對象,內部包含了一個Map對象。JSONArray代表數組,內部包含一個List對象。
Json轉String,toString()方法可以生成格式化文本。

private String writeObject() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("aString", "This is json string");
    jsonObject.put("aBoolean", true);
    jsonObject.put("aInt", 12);
    jsonObject.put("aDouble", 1.23);

    jsonObject.put("aObject", newPeopleObject("Mike", 24));

    JSONArray stringJsonArray = new JSONArray();
    stringJsonArray.put("football");
    stringJsonArray.put("basketball");
    stringJsonArray.put("volleyball");
    jsonObject.put("aStringArray", stringJsonArray);

    JSONArray objectJsonArray = new JSONArray();
    objectJsonArray.put(newPeopleObject("Jack", 26));
    objectJsonArray.put(newPeopleObject("Lily", 22));
    jsonObject.put("aObjectArray", objectJsonArray);

    String json = jsonObject.toString(4);

    return json;
}

private JSONObject newPeopleObject(String name, int age) throws JSONException {
    JSONObject peopleJsonObject = new JSONObject();
    peopleJsonObject.put("name", name);
    peopleJsonObject.put("age", age);
    return peopleJsonObject;
}

String轉Json,通過JSONObject和JSONArray的構造函數賦值。

private GsonData readObject(String json) throws JSONException {
    JSONObject jsonObject = new JSONObject(json);

    GsonData data = new GsonData();
    data.aString = jsonObject.getString("aString");
    data.aBoolean = jsonObject.getBoolean("aBoolean");
    data.aInt = jsonObject.getInt("aInt");
    data.aDouble = jsonObject.getDouble("aDouble");

    data.aObject = getPeople(jsonObject.getJSONObject("aObject"));

    JSONArray jsonArray = jsonObject.getJSONArray("aStringArray");
    data.aStringArray = new String[jsonArray.length()];
    for (int index = 0; index < jsonArray.length(); index++) {
        data.aStringArray[index] = jsonArray.getString(index);
    }

    JSONArray objectArray = jsonObject.getJSONArray("aObjectArray");
    data.aObjectArray = new People[objectArray.length()];
    for (int index = 0; index < objectArray.length(); index++) {
        data.aObjectArray[index] = getPeople(objectArray.getJSONObject(index));
    }

    return data;
}

private People getPeople(JSONObject jsonObject) throws JSONException {
    String name = jsonObject.getString("name");
    int age = jsonObject.getInt("age");
    return new People(name, age);
}

JSONObject和JSONArray提供了很多opt方法,例如getBoolean如果返回值爲null的會拋出異常,而opt方法會提供默認返回值。

public boolean getBoolean(String name) throws JSONException {
    Object object = get(name);
    Boolean result = JSON.toBoolean(object);
    if (result == null) {
        throw JSON.typeMismatch(name, object, "boolean");
    }
    return result;
}

public boolean optBoolean(String name) {
    return optBoolean(name, false);
}

public boolean optBoolean(String name, boolean fallback) {
    Object object = opt(name);
    Boolean result = JSON.toBoolean(object);
    return result != null ? result : fallback;
}

(2) JSONTokener用來解析字符串,調用nextValue()方法獲取對象。

public Object nextValue() throws JSONException {
    int c = nextCleanInternal();
    switch (c) {
        case -1:
            throw syntaxError("End of input");

        case '{':
            return readObject();

        case '[':
            return readArray();

        case '\'':
        case '"':
            return nextString((char) c);

        default:
            pos--;
            return readLiteral();
    }
}

例如

JSONTokener tokener = new JSONTokener(json);
JSONObject jsonObject = (JSONObject) tokener.nextValue();

3. Gson

(1) Gson中也提供了JsonObject和JsonArray來操作對象和數組。
Gson轉String,Gson的toJson()方法生成格式化文本。

private String writeObject() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("aString", "This is gson string");
    jsonObject.addProperty("aBoolean", true);
    jsonObject.addProperty("aInt", 12);
    jsonObject.addProperty("aDouble", 1.23);

    jsonObject.add("aObject", newPeopleObject("Mike", 24));

    JsonArray stringJsonArray = new JsonArray();
    stringJsonArray.add("football");
    stringJsonArray.add("basketball");
    stringJsonArray.add("volleyball");
    jsonObject.add("aStringArray", stringJsonArray);

    JsonArray objectJsonArray = new JsonArray();
    objectJsonArray.add(newPeopleObject("Jack", 26));
    objectJsonArray.add(newPeopleObject("Lily", 22));
    jsonObject.add("aObjectArray", objectJsonArray);

    String json = new Gson()
            .toJson(jsonObject);

    return json;
}

private JsonObject newPeopleObject(String name, int age) {
    JsonObject peopleJsonObject = new JsonObject();
    peopleJsonObject.addProperty("name", name);
    peopleJsonObject.addProperty("age", age);
    return peopleJsonObject;
}

String轉Gson,使用JsonParser解析文本獲取JsonObject。

private GsonData readObject(String json) {
    JsonObject jsonObject = (JsonObject) new JsonParser().parse(json);

    GsonData data = new GsonData();
    data.aString = jsonObject.get("aString").getAsString();
    data.aBoolean = jsonObject.get("aBoolean").getAsBoolean();
    data.aInt = jsonObject.get("aInt").getAsInt();
    data.aDouble = jsonObject.get("aDouble").getAsDouble();

    data.aObject = getPeople(jsonObject.get("aObject").getAsJsonObject());

    JsonArray jsonArray = jsonObject.get("aStringArray").getAsJsonArray();
    data.aStringArray = new String[jsonArray.size()];
    for (int index = 0; index < jsonArray.size(); index++) {
        data.aStringArray[index] = jsonArray.get(index).getAsString();
    }

    JsonArray objectArray = jsonObject.get("aObjectArray").getAsJsonArray();
    data.aObjectArray = new People[objectArray.size()];
    for (int index = 0; index < objectArray.size(); index++) {
        data.aObjectArray[index] = getPeople(objectArray.get(index).getAsJsonObject());
    }

    return data;
}

private People getPeople(JsonObject jsonObject) {
    String name = jsonObject.get("name").getAsString();
    int age = jsonObject.get("age").getAsInt();
    return new People(name, age);
}

(2) Gson序列化,利用Gson的toJson()fromJson()來實現輸入輸出。

private String writeJavaBeen() {
    GsonData data = new GsonData();
    data.aString = "This is gson string";
    data.aBoolean = true;
    data.aInt = 12;
    data.aDouble = 1.23;

    data.aObject = new People("Mike", 24);

    data.aStringArray = new String[]{"football", "basketball", "volleyball"};

    data.aObjectArray = new People[]{ new People("Jack", 26), new People("Lily", 22) };

    String json = new Gson()
            .toJson(data);

    return json;
}

private GsonData readJavaBeen(String json) {
    return new Gson().fromJson(json, GsonData.class);
}

如果是數組或者集合,也可以直接調用

new Gson().fromJson(json, String[].class)
new Gson().fromJson(json, new TypeToken<List<String>>(){}.getType())

(3) 過濾屬性,詳細可參考Android Gson使用詳解

  • @SerializedName,屬性重命名
  • @Expose,序列化和反序列化
  • @Since和@Until,根據版本過濾,對應GsonBuilder.setVersion()
  • 根據修飾符過濾,對應GsonBuilder.excludeFieldsWithModifiers()
  • 根據策略過濾,對應GsonBuilder.setExclusionStrategies()

4. FastJson

(1) FastJson中提供了JSONObject和JSONArray來操作對象和數組。
FastJson轉String,toJSONString()方法生成格式化文本。

private String writeObject() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("aString", "This is fastJson string");
    jsonObject.put("aBoolean", true);
    jsonObject.put("aInt", 12);
    jsonObject.put("aDouble", 1.23);

    jsonObject.put("aObject", newPeopleObject("Mike", 24));

    JSONArray stringJsonArray = new JSONArray();
    stringJsonArray.add("football");
    stringJsonArray.add("basketball");
    stringJsonArray.add("volleyball");
    jsonObject.put("aStringArray", stringJsonArray);

    JSONArray objectJsonArray = new JSONArray();
    objectJsonArray.add(newPeopleObject("Jack", 26));
    objectJsonArray.add(newPeopleObject("Lily", 22));
    jsonObject.put("aObjectArray", objectJsonArray);

    String json = jsonObject.toJSONString();
    return json;
}

private JSONObject newPeopleObject(String name, int age) {
    JSONObject peopleJsonObject = new JSONObject();
    peopleJsonObject.put("name", name);
    peopleJsonObject.put("age", age);
    return peopleJsonObject;
}

String轉FastJson,調用parseObject()方法獲取JSONObject。

private GsonData readObject(String json) {
    JSONObject jsonObject = JSONObject.parseObject(json);

    GsonData data = new GsonData();
    data.aString = jsonObject.getString("aString");
    data.aBoolean = jsonObject.getBooleanValue("aBoolean");
    data.aInt = jsonObject.getIntValue("aInt");
    data.aDouble = jsonObject.getDoubleValue("aDouble");

    data.aObject = getPeople(jsonObject.getJSONObject("aObject"));

    JSONArray jsonArray = jsonObject.getJSONArray("aStringArray");
    data.aStringArray = new String[jsonArray.size()];
    for (int index = 0; index < jsonArray.size(); index++) {
        data.aStringArray[index] = jsonArray.getString(index);
    }

    JSONArray objectArray = jsonObject.getJSONArray("aObjectArray");
    data.aObjectArray = new People[objectArray.size()];
    for (int index = 0; index < objectArray.size(); index++) {
        data.aObjectArray[index] = getPeople(objectArray.getJSONObject(index));
    }

    return data;
}

private People getPeople(JSONObject jsonObject) {
    String name = jsonObject.getString("name");
    int age = jsonObject.getIntValue("age");
    return new People(name, age);
}

(2) FastJson序列化,利用JSON的toJSONString()parseObject()來實現輸入輸出。

private String writeJavaBeen() {
    GsonData data = new GsonData();
    data.aString = "This is gson string";
    data.aBoolean = true;
    data.aInt = 12;
    data.aDouble = 1.23;

    data.aObject = new People("Mike", 24);

    data.aStringArray = new String[]{"football", "basketball", "volleyball"};

    data.aObjectArray = new People[]{ new People("Jack", 26), new People("Lily", 22) };

    String json = JSON.toJSONString(data);    

    return json;
}

private GsonData readJavaBeen(String json) {
    return JSON.parseObject(json, GsonData.class);
}

如果是數組或者集合,也可以直接調用

JSON.parseObject(json, String[].class)
JSON.parseObject(json, new TypeReference<List<String>>(){}.getType())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章