快速、高效解析Json数据之FastJson

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/z19980115/article/details/52005325


2018/3/27更新:【墙裂推荐】Gson解析看这里->快速、高效解析Json数据之Gson

为什么使用FastJson?
解析速度快、解析方便、使用简单。

首先,看一下解析的代码量

iu = FAST.parseObject(JsonString.JsonStringValues, info_util.class);//取得第一层JSONObject
du = FAST.parseObject(iu.getData(), info_data_util.class);//取得第二层JSONObject
olist = FAST.parseArray(du.getRows(), info_array_Util.class);//取得第三层JSONArray

没错,就两三行代码。再来看看以前常用的JsonObject以及JsonArray解析

JSONObject result= new JSONObject(jsonString);  
JSONArray jsonArray = result .getJSONArray("List");  
for (int i = 0; i < jsonArray.length; i++) {  
   JSONObject json=jsonArray.getJSONObject(i);
   json.getString("...");
   ...
   ...
}  

这种一个个去获取,很麻烦。

开始FastJson:↓

首先,需要FastJson的两个jar包,Eclipse放到项目libs目录下
可以到这里下载(任意二选一):
积分支持
免费下载链接

现在,有一串这样的Json数据:

{
    "status": 1,
    "msg": null,
    "data": {
        "start": 0,
        "limit": 10,
        "total": 5,
        "rows": [
            {
                "messageNo": "Me201607211148242364423",
                "memberNo": "AD2016070812145640900000003",
                "mobileNo": "151****1314",
                "nickname": "远方",
                "headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
                "messageType": 0,
                "readFlag": 0,
                "sendTime": 1469072904000,
                "content": "   ",
                "updateTime": 1469072904000
            },
            {
                "messageNo": "Me201607211146458551987",
                "memberNo": "AD2016070812145640900000003",
                "mobileNo": "151****1314",
                "nickname": "远方",
                "headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
                "messageType": 0,
                "readFlag": 0,
                "sendTime": 1469072805000,
                "content": "有6",
                "updateTime": 1469072805000
            },
            {
                "messageNo": "Me201607191730505629442",
                "memberNo": "AD2016070810124275700000002",
                "mobileNo": "156****3913",
                "nickname": "呵呵",
                "headPath": "/fileupload/memberImage/FD5DAE12CB79447BB5263EB0EE4E75F41469069984778.jpg",
                "messageType": 0,
                "readFlag": 0,
                "sendTime": 1468920650000,
                "content": "额",
                "updateTime": 1468920650000
            },
            {
                "messageNo": "Me201607161049255579387",
                "memberNo": "AD2016070812145640900000003",
                "mobileNo": "151****1314",
                "nickname": "远方",
                "headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
                "messageType": 1,
                "readFlag": 0,
                "sendTime": 1468637365000,
                "content": "111",
                "updateTime": 1468637365000
            },
            {
                "messageNo": "Me201607161037444613493",
                "memberNo": "AD2016070812145640900000003",
                "mobileNo": "151****1314",
                "nickname": "远方",
                "headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
                "messageType": 0,
                "readFlag": 0,
                "sendTime": 1468636664000,
                "content": "哈哈哈",
                "updateTime": 1468636664000
            }
        ],
        "otherData": null
    }
}

这串Json数据分为3层,最外层的"status",“msg"和"data”;
然后"data"里面的"start",“limit”,“total”,“rows”;最后"rows"里面的JSONArray。

源码:
JsonString.java

public class JsonString {
	public static final String JsonStringValues = "{\"status\":1,\"msg\":null,"
			+ "\"data\":{\"start\":0,\"limit\":10,\"total\":5,"
			+ "\"rows\":[{\"messageNo\":\"Me201607211148242364423\","
			+ "\"memberNo\":\"AD2016070812145640900000003\","
			+ "\"mobileNo\":\"151****1314\","
			+ "\"nickname\":\"远方\","
			+ "\"headPath\":\"/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg\","
			+ "\"messageType\":0,"
			+ "\"readFlag\":0,"
			+ "\"sendTime\":1469072904000,"
			+ "\"content\":\"   \","
			+ "\"updateTime\":1469072904000},"
			+ "{\"messageNo\":\"Me201607211146458551987\","
			+ "\"memberNo\":\"AD2016070812145640900000003\","
			+ "\"mobileNo\":\"151****1314\","
			+ "\"nickname\":\"远方\","
			+ "\"headPath\":\"/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg\","
			+ "\"messageType\":0,"
			+ "\"readFlag\":0,"
			+ "\"sendTime\":1469072805000,"
			+ "\"content\":\"有6\","
			+ "\"updateTime\":1469072805000},{\"messageNo\":\"Me201607191730505629442\",\"memberNo\":\"AD2016070810124275700000002\",\"mobileNo\""
			+ ":\"156****3913\",\"nickname\":\"呵呵\",\"headPath\":\"/fileupload/memberImage/FD5DAE12CB7944"
			+ "7BB5263EB0EE4E75F41469069984778.jpg\",\"messageType\":0,\"readFlag\":0,\"sendTime\":1468"
			+ "920650000,\"content\":\"额\",\"updateTime\":1468920650000},{\"messageNo\":\"Me2016071610"
			+ "49255579387\",\"memberNo\":\"AD2016070812145640900000003\",\"mobileNo\":\"151****1314\",\"nic"
			+ "kname\":\"远方\",\"headPath\":\"/fileupload/memberImage/83788978A0614007BF7F5D20F668088A14686"
			+ "67650848.jpg\",\"messageType\":1,\"readFlag\":0,\"sendTime\":1468637365000,\"content\":\"111\",\"upda"
			+ "teTime\":1468637365000},{\"messageNo\":\"Me201607161037444613493\",\"memberNo\":\"AD20160708121456409"
			+ "00000003\",\"mobileNo\":\"151****1314\",\"nickname\":\"远方\",\"headPath\":\"/fileupload/memberImage/8"
			+ "3788978A0614007BF7F5D20F668088A1468667650848.jpg\",\"messageType\":0,\"readFlag\":0,\"sendTime\":146"
			+ "8636664000,\"content\":\"哈哈哈\",\"updateTime\":1468636664000}],\"otherData\":null}}";

}

存储数据用的 3个 Setter and Getter封装类(因为Json数据有3层所以有3个)
info_util.java

public class info_util {
	private int status;
	private String msg, data;

	@Override
	public String toString() {
		return " status=" + status + ", msg=" + msg + ", data=" + data;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}
}

info_data_util.java

public class info_data_util {
	private int start, limit, total;
	private String rows;

	@Override
	public String toString() {
		return " start=" + start + ", limit=" + limit + ", total=" + total
				+ ", rows=" + rows;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}


	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}
}

info_array_Util.java

public class info_array_Util {
	private String messageNo, memberNo, mobileNo, nickname, headPath, content;
	private int messageType, readFlag;
	private long sendTime, updateTime;

	@Override
	public String toString() {
		return " messageNo=" + messageNo + ", memberNo="
				+ memberNo + ", mobileNo=" + mobileNo + ", nickname="
				+ nickname + ", headPath=" + headPath + ", content=" + content
				+ ", messageType=" + messageType + ", readFlag=" + readFlag
				+ ", sendTime=" + sendTime + ", updateTime=" + updateTime ;
	}

	public String getMessageNo() {
		return messageNo;
	}

	public void setMessageNo(String messageNo) {
		this.messageNo = messageNo;
	}

	public String getMemberNo() {
		return memberNo;
	}

	public void setMemberNo(String memberNo) {
		this.memberNo = memberNo;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getHeadPath() {
		return headPath;
	}

	public void setHeadPath(String headPath) {
		this.headPath = headPath;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public int getMessageType() {
		return messageType;
	}

	public void setMessageType(int messageType) {
		this.messageType = messageType;
	}

	public int getReadFlag() {
		return readFlag;
	}

	public void setReadFlag(int readFlag) {
		this.readFlag = readFlag;
	}

	public long getSendTime() {
		return sendTime;
	}

	public void setSendTime(long sendTime) {
		this.sendTime = sendTime;
	}

	public long getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(long updateTime) {
		this.updateTime = updateTime;
	}
}

然后要用的工具类,已经写好,其他项目也可以直接用,无需改动。
FAST.java

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

/**
 * 工具类
 * 
 * @author sowhat
 * 
 */
public class FAST {
	/**
	 * 解析JsonObject数据
	 * 
	 * @param jsonString
	 *            Json格式字符串
	 * @param cls
	 *            封装类
	 * 
	 */
	public static <T> T parseObject(String jsonString, Class<T> cls) {
		T t = null;
		try {
			t = JSON.parseObject(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 解析JsonArray数据
	 * 
	 * @param jsonString
	 * @param cls
	 * @return
	 */
	public static <T> List<T> parseArray(String jsonString, Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			list = JSON.parseArray(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 解析JsonArray数据,返回Map类型的List
	 * 
	 * @param jsonString
	 * @return
	 */
	public static List<Map<String, Object>> parseObjectListKeyMaps(
			String jsonString) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = JSON.parseObject(jsonString,
					new TypeReference<List<Map<String, Object>>>() {
					});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}

现在就可以解析Json数据了:↓

MainActivity.java

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.sowhat.test_fastjson.util.FAST;
import com.sowhat.test_fastjson.util.info_array_Util;
import com.sowhat.test_fastjson.util.info_data_util;
import com.sowhat.test_fastjson.util.info_util;

public class MainActivity extends Activity {
	private TextView edit;
	private info_util iu = new info_util();
	private info_data_util du = new info_data_util();
	private List<info_array_Util> olist = new ArrayList<info_array_Util>();
	private List<Map<String, Object>> mlist = new ArrayList<Map<String, Object>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edit = (TextView) findViewById(R.id.edit);
	}

	public void btn(View v) {
		/**
		 * 解析数据
		 */
		iu = FAST.parseObject(JsonString.JsonStringValues, info_util.class);//取得第一层JSONObject
		du = FAST.parseObject(iu.getData(), info_data_util.class);//取得第二层JSONObject
		olist = FAST.parseArray(du.getRows(), info_array_Util.class);//取得第三层JSONArray

		/**
		 * 打印解析结果
		 */
		StringBuffer bu = new StringBuffer();
		for (int i = 0; i < olist.size(); i++) {
			bu.append("jsonArray第" + (i + 1) + "条数据:\n"
					+ olist.get(i).toString() + "\n\n");
		}
		edit.setText("jsonObject数据:\n\n" + iu.toString() + "\n\n"
				+ du.toString() + "\n\n\n\n" + "jsonArray数据:\n" + "\n" + bu);


	}
}

布局文件: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" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/edit"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:hint="解析结果会在这里出现" />
        </LinearLayout>
    </ScrollView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btn"
        android:text="开始解析" />

</LinearLayout>

最后,看一下运行的结果:
这里写图片描述
这里写图片描述

除去必要的3个封装类,解析Json的就那么三行代码,如果Json数据结构简单甚至可能只需要一行代码。

代码已经全部贴出来了,还需要源码的可以到这里下载(任意二选一):
积分支持
免费下载链接

尊重原创,码字不易。有时间再写写用Gson解析Json数据。

展开阅读全文

没有更多推荐了,返回首页