日期:2014-05-16 浏览次数:20401 次
本文讲解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 {