2016-05-16 3 views
0

JSON形式の気象データを取得しようとしていますが、これはJSON codeです。Android JsonReader(名前はBEGIN_OBJECTでした)

URL url ; 
HttpURLConnection httpURLConnection = null; 
String result =""; 
try { 
    url=new URL(params[0]); 
    httpURLConnection = (HttpURLConnection)url.openConnection(); 
    InputStream in = httpURLConnection.getInputStream(); 
    InputStreamReader reader = new InputStreamReader(in); 

    JsonReader jsonReader = new JsonReader(reader); 
    jsonReader.beginObject(); 
    while(jsonReader.hasNext()) 
    { 
     String name = jsonReader.nextName(); 
     Log.e("jsonname",name); 

    } 
    jsonReader.endObject(); 

とログ結果は、私はすべてのJSONオブジェクトを取得していないです

jsonnametofaa: response 
java.lang.IllegalStateException: Expected a name but was BEGIN_OBJECT 
    at android.util.JsonReader.nextName(JsonReader.java:390) 
    at com.example.tofaa.myapplication.Do.doInBackground(MainActivity.java:92) 
    at com.example.tofaa.myapplication.Do.doInBackground(MainActivity.java:72) 
    at android.os.AsyncTask$2.call(AsyncTask.java:295) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
    at java.lang.Thread.run(Thread.java:818) 

です: そして、それを得るために私のコードです。

+0

「Gson」を使わない理由はありますか? –

+0

私はアンドロイド開発の新人ですが、まだGsonを知らない –

+0

[Gson](https://github.com/google/gson)、[Jackson](https:/など)などのJSONを解析する人気のあるライブラリをご覧ください。 /github.com/FasterXML/jackson)、[Moshi](https://github.com/square/moshi)。 – JJD

答えて

1

それはあなたのJSONレスポンスですイメージング:

{ 
    "foo":"bar", 
    "foo2":"bar2" 
} 

あなたはこのようにそれを解析することができます。

ModelClass.java

public class ModelClass { 
    public String foo; 
    public String foo2; 
} 

そして、あなたはこのようにGsonを使用してそれを解析することができます:

Gson gson = new Gson(); 
ModelClass instance = gson.fromJson(json, ModelClass.class); 

そして、それを追加することを忘れないでくださいまず、モデルクラスを作成する必要がありますあなたの依存関係:

compile 'com.google.code.gson:gson:2.6.1'

+0

ありがとうございました 私はこれを見つけてあなたに反応しようとします –

関連する問題