2016-04-13 48 views
3

OpenWeatherMap APIを使用すると、この例外エラーが発生します。私はちょうどの結果をとしてJSONObjectにしようとしていますが、nullが引き続き発生します。

@Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     // What's coming in as result... 
     // Printed to the console... 
     // null{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear", 
     // "description":"clear sky","icon":"01d"}],...} 


     try { 
      JSONObject jsonObject = new JSONObject(result); 
      String weatherInfo = jsonObject.getString("weather"); 

      Log.i("Weather Info", weatherInfo); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 

JSONデータは、罰金に来るが、私が望むすべては、それがJSONObjectになることですが、null部分がキャッチされています。それはなぜ起こっているのでしょうか? JSON Responseがでてくるサイトからも

は次のとおりです。

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],.....} 

どのようにそれは開始時にnullではありません来ますか? ありがとうございます。

+2

'weather'がjsonArrayは、あなたがそれに' getString'を使用することはできませんあなたの応答であるを持っていた(私のために働いた)これを試してみてください。 – Shvet

+0

@Dhaval速い返信をありがとう! – SmiffyKmc

+0

私はこの男が私を助けた前に同じ問題があります。https://stackoverflow.com/a/46127581/8582710 –

答えて

5

あなたが受け取るデータに天気はJSONArrayです。

この試してみてください:あなたは結果がnullで、サーバ起動により返された場合は、この例外org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObjectを持つことになります言ったように

String json = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],.....}"; 

try{ 
    JSONObject jo = new JSONObject(json); 
    JSONArray weather = jo.getJSONArray("weather"); 
    for(int i = 0;i < weather.length(); i++){ 
     JSONObject w = weather.getJSONObject(i); 
     String main = w.getString("main"); 
     String description = w.getString("description"); 
     //... 
    } 
}catch (Exception e){ 

} 

を。

これは、この結果が有効なJSONコンテンツではないためです。

実際にサーバーからこの無効なコンテンツを受け取った場合は、JSONを解析する前にnullを削除することで回避できます。

String crappyPrefix = "null"; 

if(result.startsWith(crappyPrefix)){ 
    result = result.substring(crappyPrefix.length(), result.length()); 
} 
JSONObject jo = new JSONObject(result); 
+0

返事をありがとう。私はまだorg.json.JSONObject型の$ _Value nullをJSONObject_に変換できません。 JSONデータが入って来るとは思えません。私が入手しているサイトは、最初はnullではありませんが、_result_で取得したときはnullになります。それは重要ですか? – SmiffyKmc

+0

私の更新された回答を参照してください... – Nirekin

+0

実際には本当に面白いです!それを説明してくれてありがとう:)しかし、私はハードコーディングされたStringをAPIからどのようにするかを学ぼうとしているので、それを使用したくありません。最新のアップデートは本当に賢いようです。私は弦の操作について忘れています。私はそれを与えるだろう!ありがとうございました。 – SmiffyKmc

0

エラーがあなたのJSONが有効でないことを意味し probabaly

あなたはJSON形式hereをテストすることができます。

しかし、あなたのコード内の問題は、あなたがのgetStringを(使用しようとしているということである)、ここで

String weatherInfo = jsonObject.getString("weather"); 

天候が実際にJSONArrayですが、あなたは文字列としてそれをしたい場合は、これを試してください

String weatherInfo = jsonObject.getJSONArray("weather").toString(); 
1

を使用、

JSONObject jsonObject = new JSONObject(result); 
     try { 
      JSONArray jsonArray = jsonObject.getJSONArray("weather"); 

      for(int i=0;i<jsonArray.length();i++){ 
       JSONObject object=jsonArray.getJSONObject(i); 
       String main =object.getString("main"); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
-1

これは私のために働いています。

JSONParser jParser = new JSONParser(); 
JSONObject weatherUrlObject =jParser.getJSONFromUrl(weatherUrl); 
try { 
     JSONArray weather = weatherUrlObject.getJSONArray("weather"); 
     WeatherNow.setWeather_id(weather.getJSONObject(0).getString("id").toString()); 
     WeatherNow.setWeather_main(weather.getJSONObject(0).getString("main").toString()); 
     WeatherNow.setWeather_description(weather.getJSONObject(0).getString("description").toString()); 
     WeatherNow.setWeather_icon(weather.getJSONObject(0).getString("icon").toString()); 
    } catch (Exception e) { 
        e.printStackTrace(); 
       } 

JSONPaserクラス:

public class JSONParser { 

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

// constructor 
public 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, "utf-8"), 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; 

} 
} 

WeatherNowは私のゲッターセッターメソッドです。

+0

'JSONParser'と' WeatherNow'とは何ですか?何も説明せずに何も投稿しないでください。 – Shvet

+0

速い返答をありがとう。私は_result_をJSONObjectになるためのメソッドに入れようとしていますが、問題が起こっているものはありません。 – SmiffyKmc

+0

String weatherInfo = jsonObject.getString( "weather"); を置き換えます。 JSONArray weather = jsonObject.getJSONArray( "weather"); –

3

は..私は同じ問題

public class DownloadData extends AsyncTask<String , Void, String >{ 

     HttpURLConnection httpURLConnection =null; 
     URL url; 


String resultString=""; <------- instead of setting it to null 


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


      try { 
       url = new URL(urls[0]); 
       httpURLConnection = (HttpURLConnection) url.openConnection(); 
       InputStream is = httpURLConnection.getInputStream(); 
       InputStreamReader isr = new InputStreamReader(is); 
       int data = isr.read(); 
       while(data != -1){ 
        char ch = (char) data; 
        resultString += ch; 
        data = isr.read(); 

       } 
       return resultString; 



      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 


      return null; 
     } 
+1

ありがとうございます。それが働いて、すべてが助けを感謝しました:) – SmiffyKmc

+1

ありがとう。これは私の問題でした。 – nuttynibbles

関連する問題