Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
jar和源码下载地址: http://code.google.com/p/google-gson/downloads/list
实体类:
- public class Student {
- private int id;
- private String name;
- private Date birthDay;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Date getBirthDay() {
- return birthDay;
- }
- public void setBirthDay(Date birthDay) {
- this.birthDay = birthDay;
- }
- @Override
- public String toString() {
- return "Student [birthDay=" + birthDay + ", id=" + id + ", name="
- + name + "]";
- }
- }
测试类:
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import com.google.gson.Gson;
- import com.google.gson.reflect.TypeToken;
- public class GsonTest1 {
- public static void main(String[] args) {
- Gson gson = new Gson();
- Student student1 = new Student();
- student1.setId(1);
- student1.setName("李坤");
- student1.setBirthDay(new Date());
- // //
- System.out.println("----------简单对象之间的转化-------------");
- // 简单的bean转为json
- String s1 = gson.toJson(student1);
- System.out.println("简单Bean转化为Json===" + s1);
- // json转为简单Bean
- Student student = gson.fromJson(s1, Student.class);
- System.out.println("Json转为简单Bean===" + student);
- // 结果:
- // 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:27:52 AM"}
- // Json转为简单Bean===Student [birthDay=Fri Jun 22 08:27:52 CST 2012, id=1,
- // name=李坤]
- // //
- Student student2 = new Student();
- student2.setId(2);
- student2.setName("曹贵生");
- student2.setBirthDay(new Date());
- Student student3 = new Student();
- student3.setId(3);
- student3.setName("柳波");
- student3.setBirthDay(new Date());
- List<Student> list = new ArrayList<Student>();
- list.add(student1);
- list.add(student2);
- list.add(student3);
- System.out.println("----------带泛型的List之间的转化-------------");
- // 带泛型的list转化为json
- String s2 = gson.toJson(list);
- System.out.println("带泛型的list转化为json==" + s2);
- // json转为带泛型的list
- List<Student> retList = gson.fromJson(s2,
- new TypeToken<List<Student>>() {
- }.getType());
- for (Student stu : retList) {
- System.out.println(stu);
- }
- // 结果:
- // 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 8:28:52 AM"}]
- // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=1, name=李坤]
- // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=2, name=曹贵生]
- // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=3, name=柳波]
- }
- }
执行结果:
- ----------简单对象之间的转化-------------
- 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:10:31 PM"}
- Json转为简单Bean===Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=1, name=李坤]
- ----------带泛型的List之间的转化-------------
- 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:10:31 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:10:31 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:10:31 PM"}]
- Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=1, name=李坤]
- Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=2, name=曹贵生]
- Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=3, name=柳波]
Json转换利器Gson之实例一-简单对象转化和带泛型的List转化 (http://blog.csdn.net/lk_blog/article/details/7685169)
Json转换利器Gson之实例二-Gson注解和GsonBuilder (http://blog.csdn.net/lk_blog/article/details/7685190)
Json转换利器Gson之实例三-Map处理(上) (http://blog.csdn.net/lk_blog/article/details/7685210)
Json转换利器Gson之实例四-Map处理(下) (http://blog.csdn.net/lk_blog/article/details/7685224)
Json转换利器Gson之实例五-实际开发中的特殊需求处理 (http://blog.csdn.net/lk_blog/article/details/7685237)
Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型 (http://blog.csdn.net/lk_blog/article/details/7685347)
实例代码下载: http://download.csdn.net/detail/lk_blog/4387822
Android中的JSON
1、JSON(JavaScript Object Notation) 定义:
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org
2、JSON的结构:
(1) Name/Value Pairs(无序的):类似所熟知的Keyed list、 Hash table、Disctionary和Associative array。
在Android平台中同时存在另外一个类 "Bundle",某种程度上具有相似的行为。
(2) Array(有序的):一组有序的数据列表。
对象
对象是一个无序的Name/Value Pairs集合。{ name:value , name:value , name:value .... }
例子:{ "name":"小猪","age":20 }
Array
Array是值(value)的有序集合。[ value , value , value ...... ]
值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。
字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。 例如:/ + " / / b f n r t u 进行转义。
例子1: Array里面包含对象(object)
[ {"id":1,"name":"小猪" ,"age”:22} , {"id":2,"name":"小猫","age”:23} , .......]
例子2:同样对象(object)中可以包含Array
(1)一个对象包含1个数组,2个子对象
{"root":[{"id":"001","name":"小猪"},{"id":"002","name":"小猫"},{"id":"003","name":"小狗"}],
"total":3,
"success":true
}
(2)也可以对象嵌套子对象,子对象再嵌套数组
{"calendar":
{"calendarlist":
[
{"id":"001","name":"小猪"},
{"id":"002","name":"小猫"}
]
}
}
总之,格式多种多样,可以互相嵌套
==================================================================================
在Android中包含四个与JSON相关的类和一个Exceptions:
JSONArray
JSONObject
JSONStringer
JSONTokener
JSONException
(1)JSONObject:
这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。
它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{“JSON”: “Hello, World”},最外被大括号包裹,其中的Key和Value被冒号”:”分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put(“JSON”, “Hello, World!”),在Key和Value之间是以逗号”,”分隔。
Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。
有两个不同的取值方法:
get(): 在确定数值存在的条件下使用,否则当无法检索到相关Key时,将会抛出一个Exception信息。
opt(): 这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认数值,并不会抛出异常。
(2)JSONArray:
它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。
同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。
(3)JSONStringer:
根据官方的解释,这个类可以帮助快速和便捷的创建JSONtext。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntaxrules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。
根据下边的实例来了解其它相关信息:
- String myString = new JSONStringer().object()
- .key("name")
- .value("小猪")
- .endObject()
- .toString();
- String myString = new JSONStringer().object()
- .key("name")
- .value("小猪")
- .endObject()
- .toString();
结果是一组标准格式的JSON text:{"name" : "小猪"}
其中的.object()和.endObject()必须同时使用,是为了按照Object标准给数值添加边界。同样,针对数组也有一组标准的方法来生成边界.array()和.endArray()。
(4)JSONTokener:
这个是系统为JSONObject和JSONArray构造器解析JSON source string的类,它可以从source string中提取数值信息。
JSONException:是JSON.org类抛出的异常信息。
下面引用一个完整的应用实例:
应用JSONObject存储Map类型数值:
- public static JSONObject getJSON(Map map) {
- Iterator iter = map.entrySet().iterator();
- JSONObject holder = new JSONObject();
- while (iter.hasNext()) {
- Map.Entry pairs = (Map.Entry) iter.next();
- String key = (String) pairs.getKey();
- Map m = (Map) pairs.getValue();
- JSONObject data = new JSONObject();
- try {
- Iterator iter2 = m.entrySet().iterator();
- while (iter2.hasNext()) {
- Map.Entry pairs2 = (Map.Entry) iter2.next();
- data.put((String) pairs2.getKey(), (String) pairs2
- .getValue());
- }
- holder.put(key, data);
- } catch (JSONException e) {
- Log.e("Transforming", "There was an error packaging JSON", e);
- }
- }
- return holder;
- }
- public static JSONObject getJSON(Map map) {
- Iterator iter = map.entrySet().iterator();
- JSONObject holder = new JSONObject();
- while (iter.hasNext()) {
- Map.Entry pairs = (Map.Entry) iter.next();
- String key = (String) pairs.getKey();
- Map m = (Map) pairs.getValue();
- JSONObject data = new JSONObject();
- try {
- Iterator iter2 = m.entrySet().iterator();
- while (iter2.hasNext()) {
- Map.Entry pairs2 = (Map.Entry) iter2.next();
- data.put((String) pairs2.getKey(), (String) pairs2
- .getValue());
- }
- holder.put(key, data);
- } catch (JSONException e) {
- Log.e("Transforming", "There was an error packaging JSON", e);
- }
- }
- return holder;
- }
下面是详细的例子:
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.net.*;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import android.util.Log;
- public class JSON {
- /**
- * 获取"数组形式"的JSON数据,
- * 数据形式:[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]
- * @param path 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List<Map<String, String>> getJSONArray(String path) throws Exception {
- String json = null;
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
- conn.setRequestMethod("GET"); // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is); // 把输入流转换成字符数组
- json = new String(data); // 把字符数组转换成字符串
- //数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]
- JSONArray jsonArray = new JSONArray(json); //数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject item = jsonArray.getJSONObject(i); //每条记录又由几个Object对象组成
- int id = item.getInt("id"); // 获取对象对应的值
- String name = item.getString("name");
- map = new HashMap<String, String>(); // 存放到MAP里面
- map.put("id", id + "");
- map.put("name", name);
- list.add(map);
- }
- }
- // ***********测试数据******************
- for (Map<String, String> list2 : list) {
- String id = list2.get("id");
- String name = list2.get("name");
- Log.i("abc", "id:" + id + " | name:" + name);
- }
- return list;
- }
- /**
- * 获取"对象形式"的JSON数据,
- * 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
- * @param path 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List<Map<String, String>> getJSONObject(String path) throws Exception {
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
- conn.setRequestMethod("GET"); // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is); // 把输入流转换成字符数组
- String json = new String(data); // 把字符数组转换成字符串
- //数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
- JSONObject jsonObject=new JSONObject(json); //返回的数据形式是一个Object类型,所以可以直接转换成一个Object
- int total=jsonObject.getInt("total");
- Boolean success=jsonObject.getBoolean("success");
- Log.i("abc", "total:" + total + " | success:" + success); //测试数据
- JSONArray jsonArray = jsonObject.getJSONArray("arrayData");//里面有一个数组数据,可以用getJSONArray获取数组
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
- int id = item.getInt("id"); // 获取对象对应的值
- String name = item.getString("name");
- map = new HashMap<String, String>(); // 存放到MAP里面
- map.put("id", id + "");
- map.put("name", name);
- list.add(map);
- }
- }
- // ***********测试数据******************
- for (Map<String, String> list2 : list) {
- String id = list2.get("id");
- String name = list2.get("name");
- Log.i("abc", "id:" + id + " | name:" + name);
- }
- return list;
- }
- /**
- * 获取类型复杂的JSON数据
- *数据形式:
- {"name":"小猪",
- "age":23,
- "content":{"questionsTotal":2,
- "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]
- }
- }
- * @param path 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List<Map<String, String>> getJSON(String path) throws Exception {
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
- conn.setRequestMethod("GET"); // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is); // 把输入流转换成字符数组
- String json = new String(data); // 把字符数组转换成字符串
- /*数据形式:
- {"name":"小猪",
- "age":23,
- "content":{"questionsTotal":2,
- "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]
- }
- }
- */
- JSONObject jsonObject=new JSONObject(json); //返回的数据形式是一个Object类型,所以可以直接转换成一个Object
- String name=jsonObject.getString("name");
- int age=jsonObject.getInt("age");
- Log.i("abc", "name:" + name + " | age:" + age); //测试数据
- JSONObject contentObject=jsonObject.getJSONObject("content"); //获取对象中的对象
- String questionsTotal=contentObject.getString("questionsTotal"); //获取对象中的一个值
- Log.i("abc", "questionsTotal:" + questionsTotal); //测试数据
- JSONArray contentArray=contentObject.getJSONArray("questions"); //获取对象中的数组
- for (int i = 0; i < contentArray.length(); i++) {
- JSONObject item = contentArray.getJSONObject(i); // 得到每个对象
- String question = item.getString("question"); // 获取对象对应的值
- String answer = item.getString("answer");
- map = new HashMap<String, String>(); // 存放到MAP里面
- map.put("question", question);
- map.put("answer", answer);
- list.add(map);
- }
- }
- // ***********测试数据******************
- for (Map<String, String> list2 : list) {
- String question = list2.get("question");
- String answer = list2.get("answer");
- Log.i("abc", "question:" + question + " | answer:" + answer);
- }
- return list;
- }
- /**
- * 把输入流转换成字符数组
- * @param inputStream 输入流
- * @return 字符数组
- * @throws Exception
- */
- public static byte[] readStream(InputStream inputStream) throws Exception {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = inputStream.read(buffer)) != -1) {
- bout.write(buffer, 0, len);
- }
- bout.close();
- inputStream.close();
- return bout.toByteArray();
- }
- }
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.net.*;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import android.util.Log;
- public class JSON {
- /**
- * 获取"数组形式"的JSON数据,
- * 数据形式:[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]
- * @param path 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List<Map<String, String>> getJSONArray(String path) throws Exception {
- String json = null;
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
- conn.setRequestMethod("GET"); // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is); // 把输入流转换成字符数组
- json = new String(data); // 把字符数组转换成字符串
- //数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]
- JSONArray jsonArray = new JSONArray(json); //数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject item = jsonArray.getJSONObject(i); //每条记录又由几个Object对象组成
- int id = item.getInt("id"); // 获取对象对应的值
- String name = item.getString("name");
- map = new HashMap<String, String>(); // 存放到MAP里面
- map.put("id", id + "");
- map.put("name", name);
- list.add(map);
- }
- }
- // ***********测试数据******************
- for (Map<String, String> list2 : list) {
- String id = list2.get("id");
- String name = list2.get("name");
- Log.i("abc", "id:" + id + " | name:" + name);
- }
- return list;
- }
- /**
- * 获取"对象形式"的JSON数据,
- * 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
- * @param path 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List<Map<String, String>> getJSONObject(String path) throws Exception {
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
- conn.setRequestMethod("GET"); // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is); // 把输入流转换成字符数组
- String json = new String(data); // 把字符数组转换成字符串
- //数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}
- JSONObject jsonObject=new JSONObject(json); //返回的数据形式是一个Object类型,所以可以直接转换成一个Object
- int total=jsonObject.getInt("total");
- Boolean success=jsonObject.getBoolean("success");
- Log.i("abc", "total:" + total + " | success:" + success); //测试数据
- JSONArray jsonArray = jsonObject.getJSONArray("arrayData");//里面有一个数组数据,可以用getJSONArray获取数组
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
- int id = item.getInt("id"); // 获取对象对应的值
- String name = item.getString("name");
- map = new HashMap<String, String>(); // 存放到MAP里面
- map.put("id", id + "");
- map.put("name", name);
- list.add(map);
- }
- }
- // ***********测试数据******************
- for (Map<String, String> list2 : list) {
- String id = list2.get("id");
- String name = list2.get("name");
- Log.i("abc", "id:" + id + " | name:" + name);
- }
- return list;
- }
- /**
- * 获取类型复杂的JSON数据
- *数据形式:
- {"name":"小猪",
- "age":23,
- "content":{"questionsTotal":2,
- "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]
- }
- }
- * @param path 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List<Map<String, String>> getJSON(String path) throws Exception {
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- conn.setConnectTimeout(5 * 1000); // 单位是毫秒,设置超时时间为5秒
- conn.setRequestMethod("GET"); // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is); // 把输入流转换成字符数组
- String json = new String(data); // 把字符数组转换成字符串
- /*数据形式:
- {"name":"小猪",
- "age":23,
- "content":{"questionsTotal":2,
- "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]
- }
- }
- */
- JSONObject jsonObject=new JSONObject(json); //返回的数据形式是一个Object类型,所以可以直接转换成一个Object
- String name=jsonObject.getString("name");
- int age=jsonObject.getInt("age");
- Log.i("abc", "name:" + name + " | age:" + age); //测试数据
- JSONObject contentObject=jsonObject.getJSONObject("content"); //获取对象中的对象
- String questionsTotal=contentObject.getString("questionsTotal"); //获取对象中的一个值
- Log.i("abc", "questionsTotal:" + questionsTotal); //测试数据
- JSONArray contentArray=contentObject.getJSONArray("questions"); //获取对象中的数组
- for (int i = 0; i < contentArray.length(); i++) {
- JSONObject item = contentArray.getJSONObject(i); // 得到每个对象
- String question = item.getString("question"); // 获取对象对应的值
- String answer = item.getString("answer");
- map = new HashMap<String, String>(); // 存放到MAP里面
- map.put("question", question);
- map.put("answer", answer);
- list.add(map);
- }
- }
- // ***********测试数据******************
- for (Map<String, String> list2 : list) {
- String question = list2.get("question");
- String answer = list2.get("answer");
- Log.i("abc", "question:" + question + " | answer:" + answer);
- }
- return list;
- }
- /**
- * 把输入流转换成字符数组
- * @param inputStream 输入流
- * @return 字符数组
- * @throws Exception
- */
- public static byte[] readStream(InputStream inputStream) throws Exception {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = inputStream.read(buffer)) != -1) {
- bout.write(buffer, 0, len);
- }
- bout.close();
- inputStream.close();
- return bout.toByteArray();
- }
- }