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