다음 코드를 사용하여 Android 애플리케이션에서 JSON을 구문 분석하고 있습니다.
JSONArray category = null;
JSONParser jParser = new JSONParser();
JSONObject json = jParser
.getJSONFromUrl("http://www.inchid.com/mobile/cate.php?cType=Product");
try {
category = json.getJSONArray("cate");
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
String name = c.getString("cate_name");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
System.out.println("ERRRORRRRRRRRRRRRRRRRRR");
}
JSONParser 클래스
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
이것은 내 응용 프로그램을 강제로 닫게 만들고 아래 그림은 logcat의 스크린 샷입니다.
Logcat 오류 :
데이터 구문 분석 오류 org.json.JSONException : java.lang.String 유형의 값 를 JSONObject로 변환 할 수 없습니다.
문자열을 작성할 때 원하지 않는 문자가 추가되었을 때 서버에서 데이터를 가져 오면 어떤 일이 발생합니다. 그래서 이것을 시도하면 도움이 될 것입니다.
json 객체 변경 만 반환하는 대신
return jObj;
...에
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
또한 소스 문자열에서 숨겨진 문자를 제거하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다