本文讲解2点:
1. fastjson生成和解析json数据
(举例:4种常用类型:JavaBean,List<JavaBean>,List<String>,List<Map<String,Object>)
2.通过一个android程序测试fastjson的用法。
fastjson简介:
Fastjson是一个Java语言编写的高性能功能完善的JSON库。fastjson采用独创的算法,将parse的速度提升到极致,超过所有json库,包括曾经号称最快的jackson。并且还超越了google的二进制协议protocol buf。Fastjson完全支持http://json.org的标准,也是官方网站收录的参考实现之一。支持各种JDK类型。包括基本类型、JavaBean、Collection、Map、Enum、泛型等。支持JDK 5、JDK 6、Android、阿里云手机等环境。
一. fastjson生成json字符串(JavaBean,List<JavaBean>,List<String>,List<Map<String,Object>)
String jsonStrng = JSON.toJSONString(object);
二. fastjson 解析json字符串为四种类型
1. JavaBean
Person person = JSON.parseObject(jsonString, Person.class);
2. List<JavaBean>
List<Person> listPerson =JSON.parseArray(jsonString, Person.class);
3. List<String>
List<String> listString = JSON.parseArray(jsonString, String.class);
4. List<Map<String,Object>>
List<Map<String, Object>> listMap = JSON.parseObject(jsonString, new TypeReference<List<Map<String,Object>>>(){}); (注意:此处可看出fastjson反射机制比gson更准确, id = 1001 通过fastjson反射仍是 id = 1001 , 而通过gson反射结果 为 id =1001.0 ,参考前篇程序运行结果图GSON方式生成和解析json数据)
-----------------------------------------------------------------------------------------------------------------------------------------
程序运行结果:
1. 点击“解析Person数据”按钮
2. 点击“解析Persons数据按钮”
3.点击“解析listString数据”按钮
4.点击“解析listMap数据”按钮
--------------------------------------------------------------------------------------------------------------------------------------
客户端eclipse android工程目录(左边)服务器端myeclipse web工程(右边)
---------------------------------------------------------------------------------------------------------------------------------------
服务器端 fastjson_Project
1.FastJsonAction.java
package com.fastjson.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.fastjson.service.FastJsonService; import com.fastjson.tools.*; public class FastJsonAction 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()); String person = FastJsonTools.createJsonString(FastJsonService.getPerson()); out.println(person); System.out.println(person); } else if("persons".equals(action_flag)) { // String persons = GsonTools.creatJsonString(GsonService.getListPersons()); String persons = FastJsonTools.createJsonString(FastJsonService.getListPersons()); out.println(persons); System.out.println(persons); }else if("listString".equals(action_flag)) { // String listString = GsonTools.creatJsonString(GsonService.getListString()); String listString = FastJsonTools.createJsonString(FastJsonService.getListString()); out.println(listString); System.out.println(listString); }else if("listMap".equals(action_flag)) { // String listMap = GsonTools.creatJsonString(GsonService.getListMap()); String listMap = FastJsonTools.createJsonString(FastJsonService.getListMap()); out.println(listMap); System.out.println(listMap); } System.out.println(); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
2.FastJsonService.java
package com.fastjson.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fastjson.data.Person; public class FastJsonService { 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.FastJsonTools.java
package com.fastjson.tools; import com.alibaba.fastjson.*; public class FastJsonTools { public static String createJsonString(Object object){ String jsonString = ""; try { jsonString = JSON.toJSONString(object); } catch (Exception e) { // TODO: handle exception } return jsonString; } }
4.Person.java
package com.fastjson.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 + "]"; } }
5. TestFastJson.java
package com.fastjson.test; import com.fastjson.service.FastJsonService; import com.fastjson.tools.FastJsonTools; public class TestFastJson { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //Test1 Person System.out.println("FastJson数据格式测试结果:\n"); String person = FastJsonTools.createJsonString(FastJsonService.getPerson()); //Test2 persons String listPerson = FastJsonTools.createJsonString(FastJsonService.getListPersons()); //Test3 listString String listString = FastJsonTools.createJsonString(FastJsonService.getListString()) ; //Test 4 listMap String listMap = FastJsonTools.createJsonString(FastJsonService.getListMap()) ; System.out.println("测试结果1:"+person+"\n"); System.out.println("测试结果2:"+listPerson+"\n"); System.out.println("测试结果3:"+listString+"\n"); System.out.println("测试结果4:"+listMap); } }
客户端:android_fastjson
1.MainActivity.java
package com.android.mygson; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.fastjson.tools.FastJsonTools; 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; 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();//关闭严苛模式 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/fastjson_Project/servlet/FastJsonAction?action_flag=person"; String jsonString = HttpUtils.getJsonContent(url_path, "utf-8"); Person person = FastJsonTools.getPerson(jsonString, Person.class); //用fastJson技术解析json字符串,转换为Person对象 // Person person = JSON.parseObject(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/fastjson_Project/servlet/FastJsonAction?action_flag=persons"; String jsonString2 = HttpUtils.getJsonContent(url_path2, "utf-8"); // 用fastjson 将json字符串转换成 List<Person> // List<Person> listPerson =JSON.parseArray(jsonString2, Person.class); List<Person> listPerson =FastJsonTools.getPersons(jsonString2, Person.class); 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/fastjson_Project/servlet/FastJsonAction?action_flag=listString"; String jsonString3 = HttpUtils.getJsonContent(url_path3, "utf-8"); // 用fastjson 将json字符串转换成 List<String> // List<String> listString = JSON.parseArray(jsonString3, String.class); List<String> listString = FastJsonTools.getPersons(jsonString3,String.class); 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/fastjson_Project/servlet/FastJsonAction?action_flag=listMap"; String jsonString4 = HttpUtils.getJsonContent(url_path4, "utf-8"); // 用fastjson 将json字符串转换成 List<Map<String,Object>> // List<Map<String, Object>> listMap = JSON.parseObject(jsonString4, new TypeReference<List<Map<String,Object>>>(){}); List<Map<String, Object>> listMap = FastJsonTools.getListMap(jsonString4); 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()); } 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; } }
2.OtherActivity.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()); // textView.setText("test :"+intent.getStringExtra("test")); } 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")); } } }
3.FastJsonTools.java
package com.fastjson.tools; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; public class FastJsonTools { /** * 用fastjson 将json字符串解析为一个 JavaBean * * @param jsonString * @param cls * @return */ public static <T> T getPerson(String jsonString, Class<T> cls) { T t = null; try { t = JSON.parseObject(jsonString, cls); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return t; } /** * 用fastjson 将json字符串 解析成为一个 List<JavaBean> 及 List<String> * * @param jsonString * @param cls * @return */ public static <T> List<T> getPersons(String jsonString, Class<T> cls) { List<T> list = new ArrayList<T>(); try { list = JSON.parseArray(jsonString, cls); } catch (Exception e) { // TODO: handle exception } return list; } /** * 用fastjson 将jsonString 解析成 List<Map<String,Object>> * * @param jsonString * @return */ public static List<Map<String, Object>> getListMap(String jsonString) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); try { // 两种写法 // list = JSON.parseObject(jsonString, new // TypeReference<List<Map<String, Object>>>(){}.getType()); list = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() { }); } catch (Exception e) { // TODO: handle exception } return list; } }
4.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 + "]"; } }
5.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; } }
6.activity_matin.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>
8.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>
-----------------------------------------------------------------------------------------------------------------
注意一点:
泛型方法
客户端:FastJsonToos.java 泛型方法的写法。