Android에서 일반 Json 해석기 사용자 정의

3122 단어 Android
일반 Json 해석기는 Json 형식을 {"status":0, "메시지":"텍스트 정보", "data":[]}로 반환합니다.
package com.suniot.caigou.parser;

import java.lang.reflect.Type;

import org.apache.http.util.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.lyh.lib.utils.DebugLog;
import com.suniot.caigou.entity.JsonResult;
import com.suniot.caigou.myenum.JsonStatus;

/**
 * @author lyh
 * @description   Json      Json   : {"status":0,"message":"    ","data":[]}
 * @date 2014-11-16
 * @param 
 */
public class JsonParser {

	private Class classOfT;
	private Type typeOfT;

	public JsonParser(Class classOfT) {
		this.classOfT = classOfT;
	}

	public JsonParser(Type typeOfT) {
		this.typeOfT = typeOfT;
	}

	/**
	 * JSON       
	 * 
	 * @param jsonStr
	 * @return
	 * @throws JSONException
	 */
	public JsonResult parseJSON(String jsonStr) throws JSONException {
		JsonResult result = new JsonResult();

		if (TextUtils.isEmpty(jsonStr)) {
			result.setStatus(JsonStatus.FAIL);
			result.setMessage("        ");
			return result;
		}

		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(jsonStr);
		} catch (Exception e) {
			DebugLog.e("           ");
			DebugLog.e(e.getLocalizedMessage());
			result.setStatus(JsonStatus.FAIL);
			result.setMessage("           ");
			return result;
		}

		try {
			int status = jsonObject.getInt("status");
			result.setStatus(JsonStatus.valueOf(status));
		} catch (Exception e) {
			DebugLog.e("  staus   status      (   Int )");
			DebugLog.e(e.getLocalizedMessage());
			result.setStatus(JsonStatus.FAIL);
			result.setMessage("           ");
			return result;
		}

		try {
			String message = jsonObject.getString("message");
			result.setMessage(message);
		} catch (Exception e) {
			DebugLog.e(e.getLocalizedMessage());
		}

		try {
			String data = jsonObject.getString("data");
			if (!TextUtils.isEmpty(data) && !data.equals("[]")
					&& !data.equals("{}")) {
				T entity = null;
				if (classOfT != null)
					entity = (T) new Gson().fromJson(data, classOfT);
				else if (typeOfT != null)
					entity = (T) new Gson().fromJson(data, typeOfT);
				result.setData(entity);
			}
		} catch (Exception e) {
			DebugLog.e(e.getLocalizedMessage());
		}

		return result;
	}
}
package com.suniot.caigou.myenum;

/**
 * @author lyh
 * @description         
 * @date 2015-04-15
 */
public enum JsonStatus {
	/**
	 *    
	 */
	NOT_LOGIN(-1),
	/**
	 *   
	 */
	FAIL(0),
	/**
	 *   
	 */
	SUCCESS(1);

	private int value = 0;

	private JsonStatus(int value) {
		this.setValue(value);
	}

	public static JsonStatus valueOf(int value) {
		switch (value) {
		case -1:
			return NOT_LOGIN;
		case 0:
			return FAIL;
		case 1:
			return SUCCESS;
		default:
			return FAIL;
		}
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

}

좋은 웹페이지 즐겨찾기