Android中自定义通用Json解释器
16lz
2021-01-23
通用Json解释器 返回Json格式为: {"status":0,"message":"文本信息","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;}}
更多相关文章
- android 6.0系统 make otapackage 错误
- 有关Android中的java.lang.ClassCastException错误
- Android SDK Manager 更新错误
- Android客户端Socket连接PC服务器端(加评论)
- android webview 中处理网页中的400、404、500等错误
- Android Studio : 导入项目出现 peer not authenticated 错误
- Android编译错误Execution failed for task ':app:transformNati
- Android读取服务器图片
- Android APK安装常见错误