Android JSON、GSON、FastJson的封装与解析

时间:2022-10-19 08:18:56

声明:
1、本帖只提供代码,不深入讲解原理。如果读者想要深入了解,那就不要在这个帖子上浪费时间了
2、客户端用的是Google官方的Volley访问服务器,具体了解Volley请戳 这里
3、本帖三种数据解析的DEMO都用到了下面这个Person类,贴出来:

 public class Person {
private String name;
private int age;
private String address; public Person() { } public Person(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
}
}

Person实体类

一、JSON的封装和解析

服务端 的代码如下:

在MyEclipse中新建一个Web Project,把JSON操作所需要的JAR包(点击这里下载)导入到项目中。

 public class JsonTools {
// 封装JSON字符串
public static String createJsonString(String key, Object value) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
}

封装JSON字符串的工具类

 public class JsonService {
public Person getPerson() {
return new Person("张三", 20, "北京");
} public List<Person> getPersons() {
List<Person> list = new ArrayList<Person>();
list.add(new Person("张三", 20, "北京"));
list.add(new Person("李四", 22, "上海"));
list.add(new Person("王五", 21, "天津"));
return list;
} public List<String> getStrings() {
List<String> list = new ArrayList<String>();
list.add("星期一");
list.add("星期二");
list.add("星期三");
list.add("星期四");
list.add("星期五");
return list;
} public List<Map<String, String>> getMaps() {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put("name", "Jack");
hashMap.put("phone", "123456789");
hashMap.put("address", "Canada");
list.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("name", "Rose");
hashMap.put("phone", "123789456");
hashMap.put("address", "America");
list.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("name", "Tom");
hashMap.put("phone", "789456123");
hashMap.put("address", "China");
list.add(hashMap);
return list;
}
}

生成几种简单类型的数据的类

 public class JsonServlet extends HttpServlet {
private JsonService service; public JsonServlet() {
super();
} public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); String key = request.getParameter("key");
if (key.equals("person")) {
Person person = service.getPerson();
out.println(JsonTools.createJsonString("person", person));
} else if (key.equals("persons")) {
List<Person> persons = service.getPersons();
out.println(JsonTools.createJsonString("persons", persons));
} else if (key.equals("strings")) {
List<String> strings = service.getStrings();
out.println(JsonTools.createJsonString("strings", strings));
} else if (key.equals("maps")) {
List<Map<String, String>> maps = service.getMaps();
out.println(JsonTools.createJsonString("maps", maps));
}
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} public void init() throws ServletException {
service = new JsonService();
}
}

测试用的Servlet类

对于输入的URL不同,结果如下:

Android JSON、GSON、FastJson的封装与解析

客户端 的代码如下:

在解析JSON时,客户端不需要导入任何包。

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff" > <TextView
android:id="@+id/person_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff000000"
android:textSize="15.0sp" /> <TextView
android:id="@+id/persons_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/person_result"
android:layout_marginTop="10.0dip"
android:textColor="#ff000000"
android:textSize="15.0sp" /> <TextView
android:id="@+id/strings_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/persons_result"
android:layout_marginTop="10.0dip"
android:textColor="#ff000000"
android:textSize="15.0sp" /> <TextView
android:id="@+id/maps_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/strings_result"
android:layout_marginTop="10.0dip"
android:textColor="#ff000000"
android:textSize="15.0sp" /> </RelativeLayout>

MainActivity类的布局代码

 public class JsonTools {
public void getResult(TextView view, JSONObject jsonObject) {
switch (view.getId()) {
case R.id.person_result:
view.setText(getPerson(jsonObject));
break;
case R.id.persons_result:
view.setText(getPersons(jsonObject));
break;
case R.id.strings_result:
view.setText(getStrings(jsonObject));
break;
case R.id.maps_result:
view.setText(getMaps(jsonObject));
break;
}
} private String getPerson(JSONObject jsonObject) {
String result = "-->从服务器获取Person数据\n";
try {
JSONObject personObject = jsonObject.getJSONObject("person");
result += "姓名:" + personObject.getString("name") + "\n";
result += "年龄:" + personObject.getString("age") + "\n";
result += "地址:" + personObject.getString("address");
} catch (JSONException e) {
e.printStackTrace();
}
return result;
} private String getPersons(JSONObject jsonObject) {
String result = "-->从服务器获取List<Person>数据\n";
try {
JSONArray jsonArray = jsonObject.getJSONArray("persons");
for (int i = 0; i < jsonArray.length(); i++) {
result += "-第" + (i + 1) + "组数据:\n";
JSONObject subObject = jsonArray.getJSONObject(i);
result += "姓名:" + subObject.getString("name") + "\n";
result += "年龄:" + subObject.getString("age") + "\n";
result += "地址:" + subObject.getString("address");
if (i != jsonArray.length() - 1) {
result += "\n";
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
} private String getStrings(JSONObject jsonObject) {
String result = "-->从服务器获取List<String>数据\n";
try {
JSONArray jsonArray = jsonObject.getJSONArray("strings");
for (int i = 0; i < jsonArray.length(); i++) {
result += jsonArray.getString(i);
if (i != jsonArray.length() - 1) {
result += " -> ";
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
} private String getMaps(JSONObject jsonObject) {
String result = "-->从服务器获取List<HashMap<String,String>>数据\n";
try {
JSONArray jsonArray = jsonObject.getJSONArray("maps");
for (int i = 0; i < jsonArray.length(); i++) {
result += "-第" + (i + 1) + "组数据:\n";
JSONObject subObject = jsonArray.getJSONObject(i);
result += "姓名:" + subObject.getString("name") + "\n";
result += "电话:" + subObject.getString("phone") + "\n";
result += "地址:" + subObject.getString("address");
if (i != jsonArray.length() - 1) {
result += "\n";
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}

处理JSON的工具类

 public class MainActivity extends Activity {
private final String url = "http://192.168.1.102:8080/JsonServer/JsonServlet";
private TextView person_result, persons_result, strings_result, maps_result;
private JsonTools jsonTools; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
person_result = (TextView) findViewById(R.id.person_result);
persons_result = (TextView) findViewById(R.id.persons_result);
strings_result = (TextView) findViewById(R.id.strings_result);
maps_result = (TextView) findViewById(R.id.maps_result);
jsonTools = new JsonTools(); getResponseToView(url + "?key=person", "json_person", person_result);
getResponseToView(url + "?key=persons", "json_persons", persons_result);
getResponseToView(url + "?key=strings", "json_strings", strings_result);
getResponseToView(url + "?key=maps", "json_maps", maps_result);
} private void getResponseToView(String url, String tag, final TextView view) {
StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject resultObject = new JSONObject(response);
jsonTools.getResult(view, resultObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
view.setText(arg0.toString());
}
});
request.setTag(tag);
MyApplication.getRequestQueue().add(request);
} @Override
protected void onStop() {
super.onStop();
MyApplication.getRequestQueue().cancelAll("JsonRequest");
}
}

主界面MainActivity的代码

运行结果如下图所示:

Android JSON、GSON、FastJson的封装与解析

二、GSON的封装和解析

服务端 的代码如下(生成数据的类GsonService和JsonService类相同,这里就不再贴了):

在MyEclipse中新建一个Web Project,将GSON操作所需要的JAR包(点击这里下载)导入到项目中。

 public class GsonTools {
// 生成GSON字符串
public static String createGsonString(Object value) {
Gson gson = new Gson();
String gsonString = gson.toJson(value);
return gsonString;
}
}

生成GSON字符串的类

 public class GsonServlet extends HttpServlet {
private GsonService service; public GsonServlet() {
super();
} public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); String key = request.getParameter("key");
if (key.equals("person")) {
Person person = service.getPerson();
out.println(GsonTools.createGsonString(person));
} else if (key.equals("persons")) {
List<Person> persons = service.getPersons();
out.println(GsonTools.createGsonString(persons));
} else if (key.equals("strings")) {
List<String> strings = service.getStrings();
out.println(GsonTools.createGsonString(strings));
} else if (key.equals("maps")) {
List<Map<String, String>> maps = service.getMaps();
out.println(GsonTools.createGsonString(maps));
}
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} public void init() throws ServletException {
service = new GsonService();
}
}

测试用的Servlet类

对于输入的URL不同,结果如下:

Android JSON、GSON、FastJson的封装与解析

客户端 的代码如下(MainActivity类的布局代码和上面的一样):

在解析GSON时,客户端需要导入和服务端相同的包。

 public class GsonTools {
public static <T> T getPerson(String jsonString, Class<T> cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return t;
} public static <T> List<T> getPersons(String jsonString, Class<T[]> cls) {
List<T> list = null;
try {
Gson gson = new Gson();
list = Arrays.asList(gson.fromJson(jsonString, cls));
} catch (Exception e) {
e.printStackTrace();
}
return list;
} public static List<String> getStrings(String jsonString) {
List<String> list = null;
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
}.getType());
} catch (Exception e) {
e.printStackTrace();
}
return list;
} public static <T> List<HashMap<String, T>> getMaps(String jsonString,Class<T> cls) {
List<HashMap<String, T>> list = new ArrayList<HashMap<String, T>>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<HashMap<String, T>>>() {
}.getType());
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}

处理受到的数据的工具类

 public class MainActivity extends Activity {
private final String url = "http://192.168.1.102:8080/GsonServer/GsonServlet";
private TextView person_result, persons_result, strings_result, maps_result; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
person_result = (TextView) findViewById(R.id.person_result);
persons_result = (TextView) findViewById(R.id.persons_result);
strings_result = (TextView) findViewById(R.id.strings_result);
maps_result = (TextView) findViewById(R.id.maps_result); getResultToView(url + "?key=person", "GsonPerson", person_result);
getResultToView(url + "?key=persons", "GsonPersons", persons_result);
getResultToView(url + "?key=strings", "GsonStrings", strings_result);
getResultToView(url + "?key=maps", "GsonMaps", maps_result);
} private void getResultToView(String url, String tag, final TextView view) {
StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
@Override
public void onResponse(String response) {
manageResponse(response, view);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
view.setText(arg0.toString());
}
});
request.setTag(tag);
MyApplication.getRequestQueue().add(request);
} // 将GsonTools类返回的处理好的JAVA对象进行排版并输出到对应TextView中
private void manageResponse(String response, TextView view) {
switch (view.getId()) {
case R.id.person_result:
addTextToView(view, "-->从服务器获取Person数据\n");
Person person = GsonTools.getPerson(response, Person.class);
addTextToView(view, "姓名:" + person.getName() + "\n年龄:" + person.getAge() + "\n地址:" + person.getAddress());
break;
case R.id.persons_result:
addTextToView(view, "-->从服务器获取List<Person>数据\n");
List<Person> persons = GsonTools.getPersons(response, Person[].class);
for (int i = 0; i < persons.size(); i++) {
Person p = persons.get(i);
addTextToView(view, "-第" + (i + 1) + "条数据\n");
addTextToView(view, "姓名:" + p.getName() + "\n年龄:" + p.getAge() + "\n地址:" + p.getAddress());
if (i != persons.size() - 1) {
addTextToView(view, "\n");
}
}
break;
case R.id.strings_result:
addTextToView(view, "-->从服务器获取List<String>数据\n");
List<String> strings = GsonTools.getStrings(response);
for (int i = 0; i < strings.size(); i++) {
addTextToView(view, strings.get(i));
if (i != strings.size() - 1) {
addTextToView(view, " -> ");
}
}
break;
case R.id.maps_result:
addTextToView(view, "-->从服务器获取List<HashMap<String,Object>>数据\n");
List<HashMap<String, String>> maps = GsonTools.getMaps(response, String.class);
for (int i = 0; i < maps.size(); i++) {
addTextToView(view, "-第" + (i + 1) + "条数据:\n");
addTextToView(view, "姓名:" + maps.get(i).get("name").toString() + "\n");
addTextToView(view, "电话:" + maps.get(i).get("phone").toString() + "\n");
addTextToView(view, "地址:" + maps.get(i).get("address").toString());
if (i != maps.size() - 1) {
addTextToView(view, "\n");
}
}
break;
}
} // 向指定TextView中添加文本
private void addTextToView(TextView view, String text) {
String currentText = view.getText().toString();
currentText += text;
view.setText(currentText);
} @Override
protected void onStop() {
super.onStop();
MyApplication.getRequestQueue().cancelAll("GsonPerson");
MyApplication.getRequestQueue().cancelAll("GsonPersons");
MyApplication.getRequestQueue().cancelAll("GsonStrings");
MyApplication.getRequestQueue().cancelAll("GsonMaps"); }
}

主界面MainActivity中的代码

运行结果如下图:
Android JSON、GSON、FastJson的封装与解析

三、FastJSON的封装和解析

服务端 的代码和使用GSON解析时的服务端代码相同(不需要改变任何东西,包括JAR包)。

客户端 的代码如下:

在解析FastJSON时,客户端需要导入解析FastJSON所需要的JAR包(点击这里下载)。

 public class FastJsonTools {
public static <T> T getPerson(String jsonString, Class<T> cls) {
T t = null;
try {
t = JSON.parseObject(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return t;
} // 解析List<Person>数据和List<String>数据都使用这个方法
public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
List<T> list = null;
try {
list = JSON.parseArray(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return list;
} public static List<HashMap<String, Object>> getMaps(String jsonString) {
List<HashMap<String, Object>> maps = new ArrayList<HashMap<String, Object>>();
try {
maps = JSON.parseObject(jsonString, new TypeReference<List<HashMap<String, Object>>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
return maps;
}
}

处理收到的数据的工具类

 public class MainActivity extends Activity {
private final String url = "http://192.168.1.102:8080/GsonServer/GsonServlet";
private TextView person_result, persons_result, strings_result, maps_result; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
person_result = (TextView) findViewById(R.id.person_result);
persons_result = (TextView) findViewById(R.id.persons_result);
strings_result = (TextView) findViewById(R.id.strings_result);
maps_result = (TextView) findViewById(R.id.maps_result); getResultToView(url + "?key=person", "FastJsonPerson", person_result);
getResultToView(url + "?key=persons", "FastJsonPersons", persons_result);
getResultToView(url + "?key=strings", "FastJsonStrings", strings_result);
getResultToView(url + "?key=maps", "FastJsonMaps", maps_result);
} private void getResultToView(String url, String tag, final TextView view) {
StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
@Override
public void onResponse(String response) {
manageResponse(view, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
addTextToView(view, arg0.toString());
}
});
request.setTag(tag);
MyApplication.getRequestQueue().add(request);
} private void addTextToView(TextView view, String text) {
String currentText = view.getText().toString();
currentText += text;
view.setText(currentText);
} private void manageResponse(TextView view, String response) {
switch (view.getId()) {
case R.id.person_result:
addTextToView(view, "-->从服务端获取Person数据\n");
Person person = FastJsonTools.getPerson(response, Person.class);
addTextToView(view,
"姓名:" + person.getName() + "\n年龄:" + person.getAddress() + "\n地址:" + person.getAddress());
break;
case R.id.persons_result:
addTextToView(view, "-->从服务器获取List<Person>数据\n");
List<Person> persons = FastJsonTools.getPersons(response, Person.class);
for (int i = 0; i < persons.size(); i++) {
Person p = persons.get(i);
addTextToView(view, "-第" + (i + 1) + "条数据\n");
addTextToView(view, "姓名:" + p.getName() + "\n年龄:" + p.getAge() + "\n地址:" + p.getAddress());
if (i != persons.size() - 1) {
addTextToView(view, "\n");
}
}
break;
case R.id.strings_result:
addTextToView(view, "-->从服务器获取List<String>数据\n");
List<String> strings = FastJsonTools.getPersons(response, String.class);
for (int i = 0; i < strings.size(); i++) {
addTextToView(view, strings.get(i));
if (i != strings.size() - 1) {
addTextToView(view, " -> ");
}
}
break;
case R.id.maps_result:
addTextToView(view, "-->从服务器获取List<HashMap<String,Object>>数据\n");
List<HashMap<String, Object>> maps = FastJsonTools.getMaps(response);
for (int i = 0; i < maps.size(); i++) {
addTextToView(view, "-第" + (i + 1) + "条数据:\n");
addTextToView(view, "姓名:" + maps.get(i).get("name").toString() + "\n");
addTextToView(view, "电话:" + maps.get(i).get("phone").toString() + "\n");
addTextToView(view, "地址:" + maps.get(i).get("address").toString());
if (i != maps.size() - 1) {
addTextToView(view, "\n");
}
}
break;
}
} @Override
protected void onStop() {
super.onStop();
MyApplication.getRequestQueue().cancelAll("FastJsonPerson");
MyApplication.getRequestQueue().cancelAll("FastJsonPersons");
MyApplication.getRequestQueue().cancelAll("FastJsonStrings");
MyApplication.getRequestQueue().cancelAll("FastJsonMaps");
}
}

主界面MainActiivty中的代码

运行结果如下图:
Android JSON、GSON、FastJson的封装与解析