2013-05-24 5 views
2

저는 Android 개발자에게 상당히 익숙하며 웹 사이트에서 일부 JSON을 구문 분석하고 ListView에 출력하는 프로그램을 작성하려고합니다.JSON 구문 분석 오류 (Android)

05-24 05:37:41.524: E/JSON Parser(783): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray 

도 내 JSON 페이지에서 XML 헤더가있을 것 같지 않기 때문에, 정말 이상한 : 내 프로그램을 실행할 때, 나는 오류가 발생합니다. whitespacing가 끔찍,

[{"codeField":"COMPSCI 101","semesterField":"Summer School; Semester 1; Semester 2","titleField":"Principles of Programming"},{"codeField":"COMPSCI 105","semesterField":"Summer School; Semester 1; Semester 2","titleField":"Principles of Computer Science"},{"codeField":"COMPSCI 111\/111G","semesterField":"Summer School; Semester 1; Semester 2","titleField":"Mastering Cyberspace: An Introduction to Practical Computing"},{"codeField":"COMPSCI 210","semesterField":"Semester 1; Semester 2","titleField":"Computer Systems 1"},{"codeField":"COMPSCI 215","semesterField":"Semester 2","titleField":"Computer Systems 2"},{"codeField":"COMPSCI 220","semesterField":"Semester 2","titleField":"Algorithms and data structures"},{"codeField":"COMPSCI 225","semesterField":"Semester 1; Semester 2","titleField":"Discrete Structures in Mathematics and Computer Science"},{"codeField":"COMPSCI 230","semesterField":"Semester 1","titleField":"Software Design and Construction"},{"codeField":"COMPSCI 230","semesterField":"Semester 2","titleField":"Software Construction"}] 

알아,하지만 내가 바꿀 수없는 외부 소스입니다 : 내가 구문 분석하는 데 노력하고있어 JSON이다. JSONParser 클래스에서

public class AndroidJSONParsingActivity extends ListActivity { 

private static String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses"; 

private static final String TAG_CODE = "codeField"; 
private static final String TAG_SEMESTER = "semesterField"; 
private static final String TAG_TITLE = "titleField"; 

JSONArray courses = null; 

    @Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> courseList = new ArrayList<HashMap<String, String>>(); 

    JSONParser jParser = new JSONParser(); 
    courses = jParser.getJSONfromURL(url); 

    try { 
     for(int i = 0; i < courses.length(); i++){ 
      JSONObject c = courses.getJSONObject(i); 

      // Storing each json item in variable 
      String code = c.getString(TAG_CODE); 
      String semester = c.getString(TAG_SEMESTER); 
      String title = c.getString(TAG_TITLE); 

      // creating new HashMap 
      HashMap<String, String> map = new HashMap<String, String>(); 

      // adding each child node to HashMap key => value 
      map.put(TAG_CODE, code); 
      map.put(TAG_SEMESTER, semester); 
      map.put(TAG_TITLE, title); 

      // adding HashList to ArrayList 
      courseList.add(map); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 


    //Updating parsed JSON data into ListView 
    ListAdapter adapter = new SimpleAdapter(this, courseList, 
      R.layout.list_item, 
      new String[] { TAG_CODE, TAG_SEMESTER, TAG_TITLE }, new int[] { 
        R.id.code, R.id.semester, R.id.title }); 

    setListAdapter(adapter); 

:

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 
    static JSONArray jArray = null; 

    public JSONParser() { 

    } 

    public JSONArray getJSONfromURL(String url) { 

     try { 
      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()); 
     } 

     // return JSON String 
     try { 
      jArray = new JSONArray(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     return jArray; 

    } 
} 

편집 :

내 코드 : 주요 활동에서

전체 로그 캣은 다음과 같습니다에만

05-24 06:48:55.347: D/dalvikvm(787): GC_CONCURRENT freed 68K, 8% free 2736K/2948K, paused 6ms+34ms, total 115ms 
05-24 06:48:55.547: E/JSON Parser(787): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray 
05-24 06:48:55.547: D/AndroidRuntime(787): Shutting down VM 
05-24 06:48:55.547: W/dalvikvm(787): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 
05-24 06:48:55.577: E/AndroidRuntime(787): FATAL EXCEPTION: main 
05-24 06:48:55.577: E/AndroidRuntime(787): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.jsonparsing/com.androidhive.jsonparsing.AndroidJSONParsingActivity}: java.lang.NullPointerException 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.access$600(ActivityThread.java:141) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.os.Handler.dispatchMessage(Handler.java:99) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.os.Looper.loop(Looper.java:137) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.main(ActivityThread.java:5041) 
05-24 06:48:55.577: E/AndroidRuntime(787): at java.lang.reflect.Method.invokeNative(Native Method) 
05-24 06:48:55.577: E/AndroidRuntime(787): at java.lang.reflect.Method.invoke(Method.java:511) 
05-24 06:48:55.577: E/AndroidRuntime(787): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
05-24 06:48:55.577: E/AndroidRuntime(787): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
05-24 06:48:55.577: E/AndroidRuntime(787): at dalvik.system.NativeStart.main(Native Method) 
05-24 06:48:55.577: E/AndroidRuntime(787): Caused by: java.lang.NullPointerException 
05-24 06:48:55.577: E/AndroidRuntime(787): at com.androidhive.jsonparsing.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:44) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.Activity.performCreate(Activity.java:5104) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 
05-24 06:48:55.577: E/AndroidRuntime(787): ... 11 more 
+0

URL을 가져 오는 중입니까? – Nezam

+0

위에서 설명한 JSON 응답이 웹에서 얻은 완전하고 정확한 응답이 아닙니다. 나는 태그로 덮여 있는지 100 % 확신합니다. 여기에 완전한 응답을 게시하십시오. –

+0

@ PareshMayani. 내가 답변을 삭제했지만, 사람도 채팅에 대한 의미는 이러한 질문의 이유를 질문해야 !! – Nezam

답변

1

..

이 URL에 POST 요청을하고 있지만이 허용되지 않습니다.당신은 그냥 http://http-headers.online-domain-tools.com/

로 이동 GET

을 입력 할 수있는 HTTP 요청을 변경하고 POST 확인 및 POST에

을 받아야 당신이 응답 받고 : 당신이 왜이

<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <title>Service</title> 
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style> 
    </head> 
    <body> 
    <div id="content"> 
     <p class="heading1">Service</p> 
     <p xmlns="">Method not allowed. Please see the <a rel="help-page" href="http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/help">service help page</a> for constructing valid requests to the service.</p> 
    </div> 
    </body> 
</html> 

이다 ' 그 오류가 다시 발생합니다!

따라서 서버에서 POST를 허용하거나 JSONParser 클래스에서 약간 변경하여 HttpPostHttpGet으로 변경할 수 있습니다. Look here

0

당신을 에서 json 배열 만들기 json 파서 클래스. 그런 다음 json 객체를 가져 오려고 시도합니다. 이 같은 json으로 파서 클래스

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 { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    return jObj; 

를 시도하고 이것이 당신이 (런타임)을 가져올 때

class LoadAllProducts extends AsyncTask<String, String, String> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(ProductsView.this); 
     pDialog.setMessage(resStrings.get(0)); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     List<NameValuePair> params1 = new ArrayList<NameValuePair>(); 
     JSONObject json = jParser.makeHttpRequest(UrlList.url_all_products, "GET", params1); 
     Log.d(resStrings.get(1), json.toString()); 
     int success = 0; 
     try { 
      success = json.getInt(TagList.TAG_SUCCESS); 
      if (success == 1) { 
       final JSONArray products = json.getJSONArray(TagList.TAG_PRODUCTS); 
       for (int i = 0; i < products.length(); i++) { 
        JSONObject c = products.getJSONObject(i); 
        String id = c.getString(TagList.TAG_PID); 
        String name = c.getString(TagList.TAG_PNAME); 
        String quantity = c.getString(TagList.TAG_PQUANTITY); 
        String price = c.getString(TagList.TAG_PPRICE); 
        String mod = c.getString(TagList.TAG_PMOD); 

        HashMap<String, String> map = new HashMap<String, String>(); 
        map.put(TagList.TAG_PID, id); 
        map.put(TagList.TAG_PNAME, name); 
        map.put(TagList.TAG_PMOD, mod); 
        map.put(TagList.TAG_PQUANTITY, quantity); 
        map.put(TagList.TAG_PPRICE, price); 
        productsList.add(map); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String file_url) { 
     pDialog.dismiss(); 
     runOnUiThread(new Runnable() { 
      @Override 
     public void run() { 
       ListAdapter adapter = new SimpleAdapter(ProductsView.this, productsList, R.layout.list_item, new String[] { TagList.TAG_PID, TagList.TAG_PNAME, TagList.TAG_PMOD, TagList.TAG_PQUANTITY, TagList.TAG_PPRICE }, new int[] { R.id.pid, R.id.pname, R.id.pmod, R.id.pquantity, R.id.pprice }); 
       setListAdapter(adapter); 
       setProductList(); 
      } 
     }); 
    } 

그래, 또한 jsonString를 사용하는 클래스가 : 나는이 있습니다 다음 클래스

public static final String MAP_ONE = "{\"width\": \"7\", \"height\": \"7\", \"walls\" : [], \"charmain\" : [[0,0]], \"charenemy\" : [[0,6],[6,6]]}"; 

클래스 공장

public class TileMapFactory { 

public static ArrayList<Point> buildMap(final String tileMapJson) throws JSONException { 

    ArrayList<Point> points = new ArrayList<Point>(); 

    final JSONObject jObject = new JSONObject(tileMapJson); 
    final JSONArray jWalls = jObject.getJSONArray("walls"); 

    for (int i = 0; i < jWalls.length(); i++) { 
     final JSONArray jWall = jWalls.getJSONArray(i); 
     points.add(new Point((Integer) jWall.get(0), (Integer) jWall.get(1))); 
    } 

    return points; 
} 

}

다음은이 같은 문자열에 액세스 할 수 있습니다 벽 문자열이 비어 예에서

walls = TileMapFactory.buildMap(tileMap); 
     for (int i = 0; i < walls.size(); i++) { 
      mWorldMap[walls.get(i).x][walls.get(i).y].setType(Tile.TYPE_WALL); 
     } 

을하지만 당신은 charenemy와 함께 벽에 태그를 교체 할 때 당신이 배열을해야합니다 2 현. 예를 들어 walls.get (i)를 호출하여 arraylist와 같은 문자열에 액세스 할 수 있습니다. codeField 같은 경우.

+0

Frank, JSON에 첫 번째 노드에 '제품'이있는 것 같습니다. 내 수업은 {{ "codeField": "COMPSCI 101"... {courses : { "codeField": "COMPSCI 101"... 대신 JSONArray를 가져 오는 방법을 모르겠습니다. 그 경우에? – misaochan

0

새 줄을 추가하면 json 문자열이 엉망이 될 수 있습니다.
"\n"이 문자열을 엉망으로 만들기 때문에 sb.append(line + "\n");sb.append(line);으로 변경하십시오.
그렇지 않으면 코드가 정상적으로 보입니다. 나는 당신의 경우에도 AsyncTask 작업을 사용하는 것이 좋습니다. Alhumdulillah.I 마침내 문제를 가지고

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); // escape will mess up your json string 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 
0

이제 작동합니다. 다들 감사 해요. :) 대신 간단히 GSON의 메소드를 사용했습니다. 훨씬 쉽습니다. 관계없이 모든 도움을 감사하십시오.

그리고 예, HttpPost도 HttpGet이어야합니다.

+0

게시물에 대한 정의를 내릴 해결책으로 내 답변을 표시해야합니다. – Nezam