Android的展现数据,除了上章所讲的本地存储外,大部分数据都来自于网络。首先介绍一下Android APP开发常见的网络操做方式。从网络层面上有底层的tcp/ip,也就是咱们常见的socket套接字,常见于IM、消息推送等应用场景。另外常见的就是Http协议、webservice协议,经常使用于提供数据接口。常应用的数据格式有xml、json。其中最多见的也就是Http+Json的组合,这也是咱们接下来要讲解的重点。在这么多项目的累计中,对于Http的访问,我用过HttpUtil这样的工具类,固然里面封装了简单的get post方法。另外也用过volley这样的集成框架。如今向你们推荐下我以为最好用的一个框架就是AsyncHttpClient。先上一段简单的示例代码。android
public final class JsonUtil {
private static String TAG = "FastJson";
public static boolean isSuccess(String jsonString) {
JSONObject json;
boolean flag = false;
try {
json = new JSONObject(jsonString);
flag = json.getBoolean("result");
} catch (JSONException e) {
e.printStackTrace();
}
return flag;
}
public static String getArrayString(String jsonString, String key) {
String value = "";
JSONObject json;
try {
json = new JSONObject(jsonString);
value = json.getJSONArray(key).toString();
} catch (JSONException e) {
e.printStackTrace();
}
return value;
}
public static String convertObjectToJson(Object o) {
SerializerFeature[] features = { SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteSlashAsSpecial,
SerializerFeature.BrowserCompatible,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat };
try {
Log.d(TAG, JSON.toJSONString(o, features));
return JSON.toJSONString(o, features);
} catch (Exception e) {
Log.e(TAG, e.toString());
return "";
}
}
public static <T> T convertJsonToObject(String json, Class<T> clazz) {
try {
return JSON.parseObject(json, clazz);
} catch (Exception e) {
Log.e(TAG, e.toString());
Log.e("merror", e.toString());
return null;
}
}
public static <T> List<T> convertJsonToList(String json, Class<T> clazz) {
try {
return JSON.parseArray(json, clazz);
} catch (Exception e) {
Log.e(TAG, e.toString());
System.out.println(e.toString());
return null;
}
}
}
public void login(final String userName, final String password, final CustomAsyncResponehandler handler) {
RequestModel requestModel = new RequestModel();
RequestParams params = new RequestParams();
params.put("userName", userName);
params.put("password", password);
requestModel.setParams(params);
requestModel.setCls(User.class);
requestModel.setShowErrorMessage(true);
requestModel.setUrl(Urls.userLogin);
httpClient.post(requestModel, new CustomAsyncResponehandler() {
@Override
public void onSuccess(ResponeModel baseModel) {
super.onSuccess(baseModel);
if (baseModel != null && baseModel.isStatus()) {
AppContext.currentUser = (User) baseModel.getResultObj();
AppContext.currentUser.setUserName(userName);
if (userDao != null) {
userDao.insert(AppContext.currentUser);
}
}
handler.onSuccess(baseModel);
}
});
}
在业务层都看不到json的解析代码了,直接经过CustomAsyncHttpClient拿到目标对象进行操做。git