Android JsonReader(预计名称但是BEGIN_OBJECT)

时间:2016-05-16 14:34:14

标签: android json

我正在尝试从此JSON code获取JSON格式的天气数据。 我的代码是:

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();

,日志结果为

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)

我没有获得所有JSON对象。

1 个答案:

答案 0 :(得分:1)

将其映像为您的JSON响应:

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

你可以像这样解析它。首先,您需要创建一个Model Class:

<强> 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'