1. Json简介
Json是一种轻量级文本数据交换格式,类似于XML,但比XML更小、更快、更易解析。
Json用于描述数据结构有两个方式
- 名称/值(JSONObject)
- 值的有序列表(JSONArray)
2. 原生Json
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(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;
}
String
转Json
,通过JSONObject
和JSONArray
的构造函数赋值。
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);
}
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;
}
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
中也提供了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(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;
}
String
转Gson
,使用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
序列化,利用Gson
的toJson()
和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
中提供了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(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;
}
String
转FastJson
,调用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
序列化,利用JSON
的toJSONString()
和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())