关于读取json和json数组的方法

/**
* 根据assets路径获取json
* @param context
* @param jsonPath json路径
* @return
*/
public JSONObject getJsonFromAssets(Context context,String jsonPath) {
InputStream in = null;
try {
in = context.getAssets().open(jsonPath);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(in, "GBK"));
   int n;
   while ((n = reader.read(buffer)) != -1) {
       writer.write(buffer, 0, n);
   }
String jsonString = writer.toString();
return new JSONObject(jsonString);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 根据assets的文件路径获取Bitmap
* @param context
* @param fileName 
* @return
*/
public Bitmap getImageFromAssets(Context context,String fileName) {
InputStream in = null;
try {
in = context.getAssets().open(fileName);
return BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

/**
* 根据assets路径获取json
* @param context
* @param jsonPath json路径
* @return
*/
public JSONArray getJsonArrayFromAssets(Context context,String jsonPath) {
InputStream in = null;
try {
System.out.println("-----jsonpath---"+jsonPath);
int end = jsonPath.lastIndexOf(".");
int start = jsonPath.lastIndexOf("/");
String name = jsonPath.substring(start+1, end);
System.out.println("-----name---"+name);
in = context.getAssets().open(jsonPath);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(in, "GBK"));
   int n;
   while ((n = reader.read(buffer)) != -1) {
       writer.write(buffer, 0, n);
   }
String jsonString = writer.toString();
JSONObject jsonObject = new JSONObject(jsonString);
return jsonObject.getJSONArray(name);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

你可能感兴趣的:(json,String,null,buffer)