JSONObject解析引發java.lang.OutOfMemoryError問題

先看代碼


需要解析的json

{"code":0,"data":[{"id":null,"name":"Doe"},{"id":2,"name":"Sam"}]}


下面代碼用JSONObject解析

	private void parseByJsonObject(String jsonStr) {
		try {
			JSONObject obj = new JSONObject(jsonStr);
			int code = obj.isNull("code") ? 0 : obj.getInt("code");
			JSONArray datas = obj.isNull("data") ? new JSONArray() : obj.getJSONArray("data");
			int length = datas.length();
			List<Person> persons = new ArrayList<Person>(length);
			for (int i = 0; i < length; i++) {
				JSONObject data = (JSONObject) datas.get(i);
				int id = data.isNull("id") ? 0 : data.getInt("id");
				String name = data.isNull("name") ? "" : data.getString("name");
				Person person = new Person();
				person.setId(id);
				person.setName(name);
				persons.add(person);
			}
			// 輸出     code=0;persons=[{"id":0,"name":"Doe",}, {"id":2,"name":"Sam",}]
			Log.e("scrat", "code="+code + ";persons="+persons.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

這是一個比較常用的, 把Json字符串轉爲JsonObject的方法


但是, 如果這個jsonStr過大, 會引發OOM異常


改用JsonReader來讀取可以避免此異常 (時間關係, 代碼有點隨意)

	@SuppressLint("NewApi")
	private void parseByJsonReader(String jsonStr) throws IOException {
		JsonReader jsonReader = null;
		InputStream in = null;
		Reader reader = null;
		try {
			in = new ByteArrayInputStream(jsonStr.getBytes());
			reader = new InputStreamReader(in, "UTF-8");
			jsonReader = new JsonReader(reader);
			
			int code = 0;
			List<Person> persons = new ArrayList<Person>();
			jsonReader.beginObject();
			while (jsonReader.hasNext()) {
				String tmpName1 = jsonReader.nextName();
				if ("code".equals(tmpName1)) {
					code = jsonReader.nextInt();
				} else if ("data".equals(tmpName1)) {
					jsonReader.beginArray();
					while (jsonReader.hasNext()) {
						int id = 0;
						String name = null;
						jsonReader.beginObject();
						while (jsonReader.hasNext()) {
							String tmpName2 = jsonReader.nextName(); // 一定要放到 jsonReader.peek()的判斷前面, 否則判斷NULL無效
							if (jsonReader.peek() == JsonToken.NULL) {
								jsonReader.skipValue();
								continue;
							}
							if ("id".equals(tmpName2)) {
								id = jsonReader.nextInt();
							} else if ("name".equals(tmpName2)) {
								name = jsonReader.nextString();
							} else {
								jsonReader.skipValue();
							}
						}
						jsonReader.endObject();
						Person person = new Person();
						person.setId(id);
						person.setName(name);
						persons.add(person);
					}
					jsonReader.endArray();
				} else {
					jsonReader.skipValue();
				}
			}
			jsonReader.endObject();
			Log.e("scrat", "code="+code + ";persons="+persons.toString());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (in != null) {
				in.close();
			}
			if (jsonReader != null) {
				jsonReader.close();
			}
		}
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章