JSONUtils

ublic class JSONUtils {

public static String getString(JSONObject response, String key) {
String value = response.optString(key, "");
return value.equals("null") ? "" : value;
}

public static boolean isEmptyArray(JSONArray jsonArray) {
return (jsonArray == null || jsonArray.length() == 0) ? true : false;
}

public static String[] decoding(JSONArray jsonArray) {
if (isEmptyArray(jsonArray)) {
return null;
}

int length = jsonArray.length();
String[] values = new String[length];
for (int i = 0; i < length; i++) {
values[i] = jsonArray.optString(i);
}
return values;
}

public static JSONArray encoding(String[] values) {
if (values == null) {
return null;
}

int length = values.length;
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < length; i++) {
try {
jsonArray.put(i, values[i]);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}

public static ArrayList<String> decodingList(JSONArray jsonArray) {
if (isEmptyArray(jsonArray)) {
return null;
}

ArrayList<String> list = new ArrayList<String>();

int length = jsonArray.length();
for (int i = 0; i < length; i++) {
String tag = jsonArray.optString(i);
if (!TextUtils.isEmpty(tag)) {
list.add(tag);
}
}
return list;
}

public static JSONArray encodingList(List<String> values) {
if (values == null) {
return null;
}

int size = values.size();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < size; i++) {
try {
jsonArray.put(i, values.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}

public static JSONArray encoding(List<Long> values) {
if (values == null) {
return null;
}

int size = values.size();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < size; i++) {
try {
jsonArray.put(i, values.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}

public static JSONObject getJSONObject(Context context, String assetsFile)
throws JSONException {
String text = readAssetRes(context, assetsFile);
return new JSONObject(text);
}

public static String readAssetRes(Context context, String filepath) {
InputStream is = null;
try {
is = context.getAssets().open(filepath);
int size = is.available();

byte[] buffer = new byte[size];
is.read(buffer);
is.close();

String text = new String(buffer, "UTF-8");
return text;
} catch (IOException e) {
e.printStackTrace();

return "";
} finally {
closeSilently(is);
}
}

private static void closeSilently(Closeable c) {
if (c == null) {
return;
}
try {
c.close();
} catch (Throwable t) {
}
}
}
--------------------- 

posted @ 2019-08-09 19:25  李艳艳665  阅读(197)  评论(0编辑  收藏  举报