2012-01-10 14 views
6

पढ़ने से पहले: मैंने इस कार्यक्रम में डाउनलोड करने योग्य जीएसओएन पुस्तकालयों का उपयोग किया था। http://webscripts.softpedia.com/script/Development-Scripts-js/Other-Libraries/Gson-71373.htmlजीएसओएन पुस्तकालयों का उपयोग कर यूआरएल (रीस्टफुल webservice) से जेएसओएन स्ट्रिंग को पार्स करना। एंड्रॉइड

मैं कुछ समय से JSON को पार्स करने का प्रयास कर रहा हूं लेकिन हर बार जब मैं यूआरएल से स्ट्रिंग प्राप्त करने का प्रयास करता हूं तो प्रोग्राम "काम" नहीं करता है। यह असफल या बंद नहीं होता है या त्रुटियां प्राप्त नहीं करता है। यह सिर्फ पार्स नहीं करता है। मेरा प्रोग्राम http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo से पार्स करने के लिए है और पार्सिंग प्रक्रिया को फिर से चलाने के लिए एक बटन है ताकि वह जानकारी को रीफ्रेश कर सके। यदि मैं एक हार्डकोडेड JSON स्ट्रिंग का उपयोग करता हूं, तो प्रोग्राम पूरी तरह से काम करता है। मैंने स्ट्रिंग में भी डाल दिया है जिसे यूआरएल से पुनर्प्राप्त किया जाना चाहिए; लेकिन मैं इसे सीधे प्राप्त करने में सक्षम नहीं लग सकता। मैं जीएसओएन पुस्तकालयों का उपयोग कर रहा हूँ।

कोड में, मैंने अपनी विचार प्रक्रिया को समझाने के लिए टिप्पणियां प्रदान की हैं। ध्यान दें कि मेरे पास 2 अलग-अलग विधियां हैं जो यूआरएल का उपयोग करने की कोशिश कर रही हैं (मैंने सोचा कि शायद मूल एक गलत था इसलिए मैंने दूसरे का उपयोग करने की कोशिश की), यह मुझे स्ट्रॉ पर पकड़ रहा था। कृपया मेरी मदद करें। धन्यवाद।

मेरे कोड:।

package com.android.testgson; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.Reader; 
import java.net.URI; 
import java.net.URL; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

import com.google.gson.Gson; 

public class GSONTestActivity extends Activity { 
    /** Called when the activity is first created. */ 

    //String test = ""; 

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

     TextView tv = (TextView)findViewById(R.id.textViewInfo); 
     syncButtonClickListener(); 

     runJSONParser(tv); 

    } 

    private void syncButtonClickListener() 
    { 

     Button syncButton = (Button)findViewById(R.id.buttonSync); 
     syncButton.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       TextView tv = (TextView)findViewById(R.id.textViewInfo); 
       runJSONParser(tv); 
      } 
     }); 
    } 


    public InputStream getJSONData(String url){ 
     // create DefaultHttpClient 
     HttpClient httpClient = new DefaultHttpClient(); 
     URI uri; // for URL 
     InputStream data = null; // for URL's JSON 

     try { 
      uri = new URI(url); 
      HttpGet method = new HttpGet(uri); // Get URI 
      HttpResponse response = httpClient.execute(method); // Get response from method. 
      data = response.getEntity().getContent(); // Data = Content from the response URL. 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return data; 
    } 

    public void runJSONParser(TextView tv){ 
     try{ 
      Gson gson = new Gson(); 
      //Reader r = new InputStreamReader(getJSONData("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo")); 
      /**I tried parsing the URL, but it didn't work. No error messages, just didn't parse.*/ 
      //Reader r = new InputStreamReader(getJSONData("android.resource://"+ getPackageName() + "/" + R.raw.yourparsable)); 
      /**I tried parsing from local JSON file. Didn't work. Again no errors. The program simply stalls. */ 

      //String testString = "{\"weatherObservation\":{\"clouds\":\"few clouds\",\"weatherCondition\":\"n/a\",\"observation\":\"LSZH 041320Z 24008KT 210V270 9999 FEW022 SCT030 BKN045 05/01 Q1024 NOSIG\",\"windDirection\":\"240\",\"ICAO\":\"LSZH\",\"elevation\":\"432\",\"countryCode\":\"CH\",\"lng\":\"8.516666666666667\",\"temperature\":\"5\",\"dewPoint\":\"1\",\"windSpeed\":\"08\",\"humidity\":\"75\",\"stationName\":\"Zurich-Kloten\",\"datetime\":\"2012-01-04 13:20:00\",\"lat\":\"47.46666666666667\",\"hectoPascAltimeter\":\"1024\"}}"; 
      /**If I parse this string. The parser works. It is the same exact string like in the URL.*/ 
      //String failString = "{\"status\":{\"message\":\"the hourly limit of 2000 credits demo has been exceeded. Please throttle your requests or use the commercial service.\",\"value\":19}}"; 
      /**Even if the url delivers this string (because the hourly limit would be reached), the string is still parsed correctly.*/ 
      String json = readUrl("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo"); 
      /**At this point I tried a different means of accessing the URL but still I had the exact same problem*/ 

      Observation obs = gson.fromJson(json, Observation.class); 
      // "json" can be replaced with r, testString, failString to see all my previous results. 

      if (obs.getWeatherObservation()!=null) 
      { 
       tv.setText("Clouds - " + obs.getWeatherObservation().getClouds() 
         + "\nTemperature - " + obs.getWeatherObservation().getTemperature() 
         + "\nWind Speed - " + obs.getWeatherObservation().getWindSpeed() 
         + "\nHumidity - " + obs.getWeatherObservation().getHumidity()); 
      } 
      else if (obs.getStatus()!=null) 
      { 
       tv.setText("Message - " + obs.getStatus().getMessage() 
         + "\nValue - " + obs.getStatus().getValue()); 
      } 

     }catch(Exception ex){ 
      ex.printStackTrace(); 
     } 

    } 

    public static String readUrl(String urlString) throws Exception { 
     BufferedReader reader = null; 

     try{ 
      URL url = new URL(urlString); 
      reader = new BufferedReader(new InputStreamReader (url.openStream())); 
      StringBuffer buffer = new StringBuffer(); 
      int read; 
      char[]chars = new char[1024]; 
      while ((read = reader.read(chars)) != -1) 
       buffer.append(chars, 0, read); 

      return buffer.toString(); 
     } finally { 
      if (reader != null) 
       reader.close(); 
     } 

    } 
} 
+0

आप पोस्ट कर सकते हैं अपने 'Observation.java'? – curioustechizen

+0

क्या आपने सत्यापित किया है कि 'readURL' वास्तव में आपके द्वारा अपेक्षित स्ट्रिंग को वापस कर रहा है? –

उत्तर

0

मैं org.json का उपयोग कर json पार्स किया है *

http://www.json.org/java/index.html एंड्रॉयड में डॉक्स 4. http://developer.android.com/reference/org/json/package-summary.html (एक उदाहरण के रूप में)

आप यहां से http://repo1.maven.org/maven2/org/json/json/20090211/json-20090211.jar

से जार डाउनलोड कर सकते हैं मैं भी चलाने पर विचार करता हूं अपने http अनुरोधों को एक अलग थ्रेड में न करें और फिर केवल अपने यूआई को दोबारा हटा दें। उस उद्देश्य के लिए android.os.Handler के बारे में भी पढ़ें।

धन्यवाद

2

तरह सेर्गेई, मैं पाया है कि Android पर शामिल json पुस्तकालय org.json.* बहुत आसान GSON से उपयोग करने के लिए है।

उदाहरण के लिए, आपके परिदृश्य में - आपका JSON पार्सिंग कोड इस तरह दिखेगा।

String jsonData = readUrl("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo"); 
JSONObject weatherJSONObject = new JSONObject(jsonData); 

try { 
    // Not sure the format of your data, but you would want something like this 
    String clouds = weatherJSONObject.getString("clouds"); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

तुम भी AsyncTask या Thread से लाभ होगा। आप यूआई थ्रेड पर लंबे समय तक चलने वाले संचालन नहीं करना चाहते हैं क्योंकि यूआई उत्तरदायी और सुस्त दिखाई देगा।

नीचे एक उदाहरण है कि आप अपने लक्ष्य को प्राप्त करने के लिए AsyncTask का उपयोग कैसे कर सकते हैं। अधिक के बारे में यह here

private class FetchJSONDataTask extends AsyncTask<String, Void, JSONObject> { 

    // This gets executed on a background thread 
    protected JSONObject doInBackground(String... params) { 
     String urlString = params[0]; 
     String jsonData = readUrl(urlString); 
     JSONObject weatherJSONObject = new JSONObject(jsonData); 
     return weatherJSONObject; 
    } 

    // This gets executed on the UI thread 
    protected void onPostExecute(JSONObject json) { 
     //Your function that takes a json object and populates views 
     setUpViews(json); 
    } 
} 

और अपने कार्य को निष्पादित करने के लिए, आप अपनी गतिविधि में इस कोड को चलाना चाहिए पढ़ें।

FetchJSONDataTask task = new FetchJSONDataTask(); 
task.execute(new String[] { "http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo" }); 

नोट: यह कोड अनचाहे है, लेकिन यह सामान्य विचार होना चाहिए।

0

JSON उत्तर सामान्य रूप से gzipped रहा है, अपने getJSONData() विधि में इस प्रयास करें:

... ... 
uri = new URI(url); 
HttpGet method = new HttpGet(uri); // Get URI 
HttpResponse response = httpClient.execute(method); // Get response from method. 
InputStream in = response.getEntity().getContent(); 
GZIPInputStream gin = new GZIPInputStream(in); 
BufferedReader reader = new BufferedReader(new InputStreamReader(gin)); 
String line = null; 
while ((line = reader.readLine()) != null) { 
    jsonResponse.append(line); 
} 
reader.close(); 
... ... 
संबंधित मुद्दे