2013-12-10 3 views
0

나는 하루 동안 해결책을 찾았으며 내 상황에 적용 할 해결책을 찾지 못했습니다. 유감 스럽지만 JSON (독학 프로그래머)을 처음 접했을 때 어떤 수업을 게시해야하는지 모르기 때문에 내가 가지고있는 모든 것을 넣을 것입니다. 나는 로그 캣에서 다음과 같은 오류가 점점 오전 :JSON 데이터 구문 분석 문제

package com.example.mytravelbuddy; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.ImageView; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

public class Itinerary extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    //JSON Parser 
    JSONParser jParser = new JSONParser(); 

    //URL To Get Products 
    public static String url = "URL REMOVED"; //Removed my url since i was hosting online 

    //JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_ITEMS = "items"; 
    private static final String TAG_ID = "ID"; 
    private static final String TAG_LOCATION = "Location"; 
    private static final String TAG_DESCRIPTION = "Description"; 
    private static final String TAG_LATITUDE = "Latitude"; 
    private static final String TAG_LONGITUDE = "Longitude"; 
    private static final String TAG_TIME = "Time"; 

    //Array list 
    ArrayList<HashMap<String, String>> itemList; 

    //Items JSONArray 
    JSONArray items = null; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_starting_point); 

     itemList = new ArrayList<HashMap<String, String>>(); 

     new LoadAllItems().execute(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.starting_point, menu); 
     return true; 
    } 

    class LoadAllItems extends AsyncTask<String, String, String>{ 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(Itinerary.this); 
      pDialog.setMessage("Loading items. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 


     @Override 
     protected String doInBackground(String... arg0) { 

      //Building Params 
      List<NameValuePair> params = new ArrayList<NameValuePair>();   

      //Getting JSON String 
      JSONObject json = jParser.makeHttpRequest(url, "GET", params); 

      try{ 
       //Getting array of items 
       Log.i("Error","ERROR 1"); //This error message is displayed 
       items = json.getJSONArray(TAG_ITEMS); //This is the line that is giving me a problem 
       Log.i("Error","ERROR 2"); //This error message is not displayed 

       //Looping through 
       for(int i = 0; i < items.length();i++){ 

        JSONObject c = items.getJSONObject(i); 

        //Storing JSON item in variable 
        String location = c.getString(TAG_LOCATION); 
        String description = c.getString(TAG_DESCRIPTION); 
        String longitude = c.getString(TAG_LONGITUDE); 
        String latitude = c.getString(TAG_LATITUDE); 
        String time = c.getString(TAG_TIME); 


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

        //Put value in hashmap map 
        map.put(TAG_LOCATION, location); 
        map.put(TAG_DESCRIPTION, description); 
        map.put(TAG_LONGITUDE, longitude); 
        map.put(TAG_LATITUDE, latitude); 
        map.put(TAG_TIME, time); 

        itemList.add(map); 
       } 
      }catch(JSONException e){ 
       e.printStackTrace(); 
      } 

      return null; 
     }} 
} 

내가있는 줄을 내가 로그 캣에서 오류 메시지를 표시하여 오류를 얻고있다 발견

Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray 

여기 내 클래스입니다. 내 JSON 파서 클래스

다음
{ 
    "items": [ 
     { 
      "ID": "1", 
      "Location": "TEST", 
      "Description": "TEST DESC", 
      "Latitude": "1", 
      "Longitude": "2", 
      "Time": "3:00" 
     }, 
     { 
      "ID": "2", 
      "Location": "TEST2", 
      "Description": "TEST2 DESC", 
      "Latitude": "1", 
      "Longitude": "1", 
      "Time": "7:00" 
     }, 
     { 
      "ID": "3", 
      "Location": "TEST3", 
      "Description": "TEST3 DESC", 
      "Latitude": "3", 
      "Longitude": "4", 
      "Time": "12:00" 
     } 
    ], 
    "success": 1 
} 

은 다음과 같습니다 :

여기
<?php 

$user = "root"; 
$pass = ""; 
$database = "travel_buddy"; 
$server = "127.0.0.1"; 

mysql_connect($server, $user, $pass); 
    $db_found = mysql_select_db($database); 
    if($db_found){ 
     echo"DB Found<br>"; 
    }else{ 
     echo"DB NOT Found<br>"; 
    } 
echo"Connection Established<br>"; 
get_details(); 


function get_details(){ 
$response = array(); 
$result = mysql_query("SELECT *FROM adventure"); 

if(mysql_num_rows($result)>0){ 
    $response["items"] = array(); 

    while($row = mysql_fetch_array($result)){ 
     $info = array(); 
     $product["ID"] = $row["ID"]; 
     $product["Location"] = $row["Location"]; 
     $product["Description"] = $row["Description"]; 
     $product["Latitude"] = $row["Latitude"]; 
     $product["Longitude"] = $row["Longitude"]; 
     $product["Time"] = $row["Time"]; 

     array_push($response["items"], $product); 
    } 
     $response["success"] = 1; 

     echo json_encode($response); 
} else { 
    $response["success"] = 0; 
    $response["message"] = "No Information Found"; 

    echo json_encode($response); 
} 

} 

?> 

내 JSON 응답입니다 : 여기

내가로부터 응답을 얻기 위해 노력하고 있어요 내 PHP 파일입니다

package com.example.mytravelbuddy; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

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

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       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; 

    } 
} 

도움이 될 것입니다. 왜이 오류가 발생했는지 설명 할 수 있으므로 다시 반복하지 마십시오.

+2

JSON 대신 XML이 전송 된 것으로 보입니다. –

+0

또한이'method == "GET"'이 잘못되었습니다. 문자열을 비교할 때'.equals'을 사용하십시오. –

+0

예 그 부분을 알고 있습니다. 내가 모르는 것은 그것을 고치는 방법이다. 데이터베이스에 문제가 있습니까? – Trifecta

답변

0

이 서비스가 다른 일을 반향되는 문제

mysql_connect($server, $user, $pass); 
    $db_found = mysql_select_db($database); 
    if($db_found){ 
     echo"DB Found<br>"; 
    }else{ 
     echo"DB NOT Found<br>"; 
    } 
echo"Connection Established<br>"; 

발생할 수 있습니다. JSON을 echo'ing해야합니다.


대신에 그러한 정보는 헤더 가지고하는 것이 중요하다 또한
mysql_connect($server, $user, $pass); 
    $db_found = mysql_select_db($database); 
    if($db_found){ 
     error_log("DB Found<br>"); 
    }else{ 
     error_log("DB NOT Found<br>)"; 
    } 
error_log("Connection Established<br>"); 

기록 될 수 있습니다 : 스크립트의 상단에

header("Content-Type: application/json"); 

장소를.

편집 : 방금 ​​코드를 시도했지만 오류없이 JSON을 구문 분석 할 수 있습니다.

PHP 서버가 어떤 이유로 XML을 전송하고있을 가능성이 큽니다. 해당 스크립트를 다시 확인해야합니다. 인코딩 된 json을 엉망으로 만드는 오류를보고 할 수도 있으며, 오류를 기록하지만 JSON 만 표시 할 수도 있습니다.

희망이 도움이됩니다.

+0

나는 그 라인을 바 꾸었고 나의 어플리케이션은 여전히 ​​같은 에러로 인해 충돌했다. – Trifecta

+0

머리글은 여전히 ​​작동하지 않습니다. – Trifecta

+0

@ user2904544 난 그냥 귀하의 코드와 그 완벽한 작업을 시도, 당신은 제대로 JSON을 echo'ing, PHP는 문제를 해결할 수있다 – meda

0

PHP 페이지가 json (만) 대신 다른 문자열을 표시합니다.

+0

에코 라인이 제거되었습니다. 아직도 작동하지 않습니다. – Trifecta

+0

구문 분석 전에 json 문자열을 인쇄하십시오. –

0

JSON 응답을 구문 분석하려면 Gson을 사용하는 것이 좋습니다. 같을 것이다 클래스 위의 예를 들어

:

public class ItemList { 
    List<Item> items; 
} 

Item은 다음과 같습니다

public class Item { 
    private String ID; 
    private String Location; 
    private String Description; 
    private String Longitude; 
    private String Latitude; 
    private String Time; 
} 

그런 다음, 구문 분석이 절대적으로 사소한된다.을 libs 폴더에 넣은 다음이 작업을 수행하십시오.

Gson GSON = new Gson(); 
ItemList itemList = GSON.fromJson(json_string_here, ItemList.class); 

그게 전부입니다. 당신은 JSON에서 파싱 된 1 급 자바 객체를 가지고있다. 쉽고 강력합니다.

+0

Gson을 사용할 경우 파서 클래스가 필요하지 않습니까? – Trifecta

+0

여전히 서버를 제공하는 서버에서 JSON을 다운로드해야하지만'jObj = new JSONObject (json); '를 더 이상 사용할 필요가 없습니다. –