客户端与服务器进行数据交互时,常常需要将数据在服务器端将数据转化成字符串并在客户端对json数据进行解析生成对象。但是用jsonObject和jsonArray解析相对麻烦。利用Gson和阿里的fastjson可以很方便的将下面四种常用的数据转换成json字符串,并能够将其解析成原数据对象。
类型一:JavaBean
类型二:List<JavaBean>
类型三:List<String>
类型四:List<Map<String,Object>>
一.Gson将上面的四种数据对象转换成json字符串的方法都是一样的
Gson gson = new Gson();
String jsonString = gson.toJson(obj);
二.Gson将json字符串转化成JavaBean对象
1.类型一:JavaBean
Person person = new Person("香港","刘德华",1001);
Gson gson = new Gson();
//这里将javabean转化成json字符串
String jsonString = gson.toJson(person);
System.out.println(jsonString);
//这里将json字符串转化成javabean对象,
person = gson.fromJson(jsonString,Person.class);
2.类型二:List<JavaBean>
将json字符串转化成List<JavaBean>对象
Person person1 = new Person("香港","刘德华",1001);
Person person2 = new Person("韩国","宋慧乔",1002);
List<Person> persons = new ArrayList<Person>();
persons.add(person1);
persons.add(person2);
Gson gson = new Gson();
//这里将lsit<javabean>转化成json字符串
String jsonString = gson.toJson(persons);
//解析json字符串
List<Person> persons2 = gson.fromJson(jsonString, new TypeToken<List<Person>>(){}.getType());
3.类型三:List<String>
将json字符串转化成List<String>对象
List<String> list = new ArrayList<String>();
list.add("gson1");
list.add("gson2");
list.add("gson3");
Gson gson = new Gson();
String jsonString = gson.toJson(list);
System.out.println("json字符串:"+jsonString);
//解析json字符串
List<String> list2 = gson.fromJson(jsonString, new TypeToken<List<String>>(){}.getType());
4.类型四:List<Map<String,Object>>
将json字符串转化成List<Map<String,Object>>对象
Map<String,Object> map = new HashMap<String,Object>();
map.put("key1", "value1");
map.put("key2", "value2");
Map<String,Object> map2 = new HashMap<String,Object>();
map2.put("key1", 1);
map2.put("key2", 2);
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
list.add(map);
list.add(map2);
Gson gson = new Gson();
String jsonString = gson.toJson(list);
System.out.println("json字符串:"+jsonString);
//解析json字符串
List<Map<String,Object>> list2 = gson.fromJson(jsonString, new TypeToken<List<Map<String,Object>>>(){}.getType());
--------------------------------------------------------------------------------------------------------------------------------
本程序服务器端通过Gson生成json字符串数据,客户端用Gson将从服务器端接收的json字符串分别转换为<Person>,List<Person>,List<String>,List<Map<String,Object>>4种类型,程序思路和过程跟前篇 android Intent传递 object , list<object>,list<Map<String,Object>> 相同,唯一区别就是:生成json用Gson方式,解析json用Gson方式。
程序结果截图:
1.点击“解析Person数据”按钮
3.点击“解析Persons”数据按钮
4.点击“解析listString数据”按钮
5.点击“解析listMap数据”按钮
---------------------------------------------------------------------------------------------------------------------------------------
客户端eclipse android工程目录(左边)服务器端myeclipse web工程目录(右边)
服务器端
1.Person.java
package com.gson.data; public class Person { private int id; private String name; private String address; public Person() { // TODO Auto-generated constructor stub } 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person(int id, String name, String address) { super(); this.id = id; this.name = name; this.address = address; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", address=" + address + "]"; } }
2.GsonService.java
package com.gson.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.gson.data.Person; public class GsonService { public static Person getPerson() { Person person = new Person(1001, "刘德华", "香港"); return person; } public static List<Person> getListPersons() { List<Person> persons = new ArrayList<Person>(); Person person1 = new Person(1001, "刘德华", "香港"); Person person2 = new Person(1002, "宋慧乔", "韩国"); persons.add(person1); persons.add(person2); return persons; } public static List<String> getListString(){ List<String> list = new ArrayList<String>(); list.add("美国"); list.add("中国"); list.add("俄罗斯"); return list; } public static List<java.util.Map<String, Object>> getListMap(){ List<java.util.Map<String, Object>> list = new ArrayList<Map<String,Object>>(); java.util.Map<String,Object> map1 = new HashMap<String,Object>(); map1.put("id",1001); map1.put("name","刘德华"); map1.put("address","香港"); java.util.Map<String,Object> map2 = new HashMap<String,Object>(); map2.put("id",1002); map2.put("name","宋慧乔"); map2.put("address","韩国"); list.add(map1); list.add(map2); return list; } }
3.GsonTools.java
package com.gson.tools; import com.google.gson.Gson; public class GsonTools { public static String creatJsonString(Object object) { Gson gson = new Gson(); String jsonString = gson.toJson(object); // 用Gson方式 把object 保存为 json字符串 return jsonString; } }
4.GsonAction.java
package com.gson.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gson.service.GsonService; import com.gson.tools.GsonTools; public class GsonAction extends HttpServlet { /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String action_flag = request.getParameter("action_flag"); PrintWriter out = response.getWriter(); if ("person".equals(action_flag)) { String person = GsonTools.creatJsonString(GsonService.getPerson()); out.println(person); } else if("persons".equals(action_flag)) { String persons = GsonTools.creatJsonString(GsonService.getListPersons()); out.println(persons); }else if("listString".equals(action_flag)) { String listString = GsonTools.creatJsonString(GsonService.getListString()); out.println(listString); }else if("listMap".equals(action_flag)) { String listMap = GsonTools.creatJsonString(GsonService.getListMap()); out.println(listMap); } out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
5. TestGson.java
package com.gson.test; import com.gson.service.GsonService; import com.gson.tools.GsonTools; public class TestGson { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //Test1 Person System.out.println("Gson数据格式测试结果:\n"); String person = GsonTools.creatJsonString(GsonService.getPerson()) ; //Test2 persons String listPerson = GsonTools.creatJsonString(GsonService.getListPersons()) ; //Test3 listString String listString = GsonTools.creatJsonString(GsonService.getListString()) ; //Test 4 listMap String listMap = GsonTools.creatJsonString(GsonService.getListMap()) ; System.out.println("测试结果1:"+person+"\n"); System.out.println("测试结果2:"+listPerson+"\n"); System.out.println("测试结果3:"+listString+"\n"); System.out.println("测试结果4:"+listMap); } }
客户端
1.Person.java
package com.gson.data; import java.io.Serializable; public class Person implements Serializable{ private int id; private String name; private String address; public Person() { // TODO Auto-generated constructor stub } 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person(int id, String name, String address) { super(); this.id = id; this.name = name; this.address = address; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", address=" + address + "]"; } }
2.HttpUtils.java
package com.gson.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.annotation.SuppressLint; import android.os.StrictMode; /** 接收path服务器端返回的 InputStream, 转换为 json字符串 * @author ben * */ public class HttpUtils { public static String getJsonContent(String url_path ,String encode){ String jsonString = ""; try { URL url = new URL(url_path); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(3000); connection.setRequestMethod("GET"); connection.setDoInput(true); //从服务器获得数据 int responseCode = connection.getResponseCode(); if (200 == responseCode) { jsonString = changeInputStream(connection.getInputStream(),encode); } } catch (Exception e) { // TODO: handle exception } // return jsonString; } private static String changeInputStream(InputStream inputStream , String encode) throws IOException { // TODO Auto-generated method stub String jsonString = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; while((len=inputStream.read(data))!=-1){ outputStream.write(data, 0, len); } jsonString = new String(outputStream.toByteArray(), encode); inputStream.close(); return jsonString; } }
3.MainActivity.java
package com.android.mygson; import java.io.Serializable; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.gson.data.Person; import com.gson.http.HttpUtils; import android.os.Bundle; import android.os.StrictMode; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.google.gson.reflect.TypeToken; ; public class MainActivity extends Activity implements OnClickListener { private Button person, persons, listString, listMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); closeStrictMode(); // closeStrictMode(); //关闭严苛模式 person = (Button) findViewById(R.id.person); persons = (Button) findViewById(R.id.persons); listString = (Button) findViewById(R.id.listString); listMap = (Button) findViewById(R.id.listMap); person.setOnClickListener(this); persons.setOnClickListener(this); listString.setOnClickListener(this); listMap.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.person: String url_path = "http://192.168.0.102:8080/gsonProject/servlet/GsonAction?action_flag=person"; String jsonString = HttpUtils.getJsonContent(url_path, "utf-8"); Gson gson = new Gson(); Person person = gson.fromJson(jsonString, Person.class); Intent intent = new Intent(MainActivity.this, OtherActivity.class); intent.putExtra("click_flag", "person"); intent.putExtra("person", (Serializable) person); startActivity(intent); // Log.i(TAG, person.toString()); break; case R.id.persons: String url_path2 = "http://192.168.0.102:8080/gsonProject/servlet/GsonAction?action_flag=persons"; String jsonString2 = HttpUtils.getJsonContent(url_path2, "utf-8"); Gson gson2 = new Gson(); // 用GSON 将json字符串转换成 List<Person> List<Person> listPerson = gson2.fromJson(jsonString2,new TypeToken<List<Person>>(){}.getType()); Intent intent2 = new Intent(MainActivity.this, OtherActivity.class); intent2.putExtra("click_flag", "persons"); intent2.putExtra("persons", (Serializable) listPerson); // 用Intent传递 List<Person>数据类型 startActivity(intent2); break; case R.id.listString: String url_path3 = "http://192.168.0.102:8080/gsonProject/servlet/GsonAction?action_flag=listString"; String jsonString3 = HttpUtils.getJsonContent(url_path3, "utf-8"); Gson gson3 = new Gson(); // 用GSON 将json字符串转换成 List<String> List<String> listString = gson3.fromJson(jsonString3,new TypeToken<List<String>>(){}.getType()); Intent intent3 = new Intent(MainActivity.this, OtherActivity.class); intent3.putExtra("click_flag", "listString"); intent3.putExtra("listString", (Serializable) listString); // 用Intent传递 List<Person>数据类型 startActivity(intent3); break; case R.id.listMap: String url_path4 = "http://192.168.0.102:8080/gsonProject/servlet/GsonAction?action_flag=listMap"; String jsonString4 = HttpUtils.getJsonContent(url_path4, "utf-8"); Gson gson4 = new Gson(); // 用GSON 将json字符串转换成 List<Map<String,Object>> List<Map<String, Object>> listMap = gson4.fromJson(jsonString4, new TypeToken<List<Map<String, Object>>>() {}.getType()); Intent intent4 = new Intent(MainActivity.this, OtherActivity.class); intent4.putExtra("click_flag", "listMap"); intent4.putExtra("listMap", (Serializable) listMap); // 用Intent传递 List<Map<Sting,Object>>数据类型 intent4.putExtra("jsonString", jsonString4); startActivity(intent4); break; } } @SuppressLint("NewApi") public static void closeStrictMode() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll().penaltyLog().build()); } }
4.OtherActvity.java
package com.android.mygson; import java.util.List; import java.util.Map; import com.gson.data.Person; import android.R.integer; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class OtherActivity extends Activity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); textView = (TextView) findViewById(R.id.msg); Intent intent = getIntent(); String click_flag = intent.getStringExtra("click_flag"); if ("person".equals(click_flag)) { // 如果是点击 person按钮 // 接收Intent传递的Person对象 Person person =(Person) intent.getSerializableExtra("person"); textView.setText(person.toString()); } else if ("persons".equals(click_flag)) {// 如果是点击 persons按钮 // 接收Intent传递的List<Person>参数 @SuppressWarnings("unchecked") List<Person> list = (List<Person>) intent .getSerializableExtra("persons"); String persons = ""; for (Person person : list) { persons += person.toString() + "\n"; } textView.setText(persons); }else if ("listString".equals(click_flag)) { List<String> list = (List<String>) intent .getStringArrayListExtra("listString"); String listString = ""; for (String s : list) { listString += s + "\n"; } textView.setText(listString); } else if ("listMap".equals(click_flag)) { //接收Intent传递的List<Map<String,Object>>参数 @SuppressWarnings("unchecked") List<Map<String, Object>> list = (List<Map<String, Object>>) intent .getSerializableExtra("listMap"); String listMapString = ""; for (Map<String, Object> map : list) { // 遍历一个Map for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); listMapString += " " + key + " : " + value + " "; } listMapString += "\n"; } textView.setText(listMapString+intent.getStringExtra("jsonString")); } } }
5.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.mygson" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <!-- 添加访问网络的授权 --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.android.mygson.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".OtherActivity"></activity> </application> </manifest>
6.activity_main.xml
<LinearLayout 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:orientation="vertical"> <Button android:id="@+id/person" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析Person数据" /> <Button android:id="@+id/persons" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析Persons数据" /> <Button android:id="@+id/listString" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析listString数据" /> <Button android:id="@+id/listMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析listMap数据" /> </LinearLayout>
7.activity_other.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/msg" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>