Android Json应用

1. Json简介

Json是一种轻量级文本数据交换格式,类似于XML,但比XML更小、更快、更易解析。

Json用于描述数据结构有两个方式

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

2. 原生Json

JSONObject表示json对象,内部包含了一个Map对象。JSONArray代表数组,内部包含一个List对象。

JsonStringtoString()方法可以生成格式化文本。

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(1, "Mike", "ShengZhen", 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(2, "Jack", "ShangHai", 26));
    objectJsonArray.put(newPeopleObject(3, "Lily", "BeiJing", 22));
    jsonObject.put("aObjectArray", objectJsonArray);

    String json = jsonObject.toString(4);

    return json;
}

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

StringJson,通过JSONObjectJSONArray的构造函数赋值。

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

    JsonData data = new JsonData();
    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 {
    int id = jsonObject.getInt("id");
    String name = jsonObject.getString("name");
    String addr = jsonObject.getString("addr");
    int age = jsonObject.getInt("age");
    return new People(name, age);
}

JSONObjectJSONArray提供了很多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;
}

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

Gson中也提供了JsonObjectJsonArray来操作对象和数组。

GsonStringGsontoJson()方法生成格式化文本。

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(1, "Mike", "ShengZhen", 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(2, "Jack", "ShangHai", 26));
    objectJsonArray.add(newPeopleObject(3, "Lily", "BeiJing", 22));
    jsonObject.add("aObjectArray", objectJsonArray);

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

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

StringGson,使用JsonParser解析文本获取JsonObject

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

    JsonData data = new JsonData();
    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) {
    int id = jsonObject.get("id").getAsInt();
    String name = jsonObject.get("name").getAsString();
    String addr = jsonObject.get("addr").getAsString();
    int age = jsonObject.get("age").getAsInt();
    return new People(name, age);
}

Gson序列化,利用GsontoJson()fromJson()来实现输入输出。

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

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

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

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

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

    return json;
}

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

如果是数组或者集合,也可以直接调用

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

过滤属性,详细可参考Android Gson使用详解

  • @SerializedName,属性重命名
  • @Expose,序列化和反序列化
  • @Since@Until,根据版本过滤,对应GsonBuilder.setVersion()
  • 根据修饰符过滤,对应GsonBuilder.excludeFieldsWithModifiers()
  • 根据策略过滤,对应GsonBuilder.setExclusionStrategies()

4. FastJson

FastJson中提供了JSONObjectJSONArray来操作对象和数组。

FastJsonStringtoJSONString()方法生成格式化文本。

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(1, "Mike", "ShengZhen", 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(2, "Jack", "ShangHai", 26));
    objectJsonArray.add(newPeopleObject(3, "Lily", "BeiJing", 22));
    jsonObject.put("aObjectArray", objectJsonArray);

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

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

StringFastJson,调用parseObject()方法获取JSONObject

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

    JsonData data = new JsonData();
    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) {
    int id = jsonObject.getIntValue("id");
    String name = jsonObject.getString("name");
    String addr = jsonObject.getString("addr");
    int age = jsonObject.getIntValue("age");
    return new People(name, age);
}

FastJson序列化,利用JSONtoJSONString()parseObject()来实现输入输出。

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

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

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

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

    String json = JSON.toJSONString(data);    

    return json;
}

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

如果是数组或者集合,也可以直接调用

JSON.parseObject(json, String[].class)
JSON.parseObject(json, new TypeReference<List<String>>(){}.getType())

相关文章
Android Xml文件操作
Android Json应用

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值