Android Json应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chennai1101/article/details/82179446

相关文章
Android 文件操作
Android SQLite应用
Android Xml文件操作
Android SharedPreferences应用
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())

猜你喜欢

转载自blog.csdn.net/chennai1101/article/details/82179446
今日推荐