Java 解析 Android Volley JSONArray 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24401094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:00:10  来源:igfitidea点击:

Parse Android Volley JSONArray response

javaandroidjsonandroid-volley

提问by settheline

I'm sending a JSONArray GET request with Volley, and it's returning the specified JSON array. Here's my Request:

我正在使用 Volley 发送一个 JSONArray GET 请求,它返回指定的 JSON 数组。这是我的请求:

JsonArrayRequest getRequest = new JsonArrayRequest(url,
                    new Response.Listener<JSONArray>()
                    {
                        @Override public void onResponse(JSONArray response) {

                            Log.d("Response", response.toString());
                        }
                    },
                    new Response.ErrorListener()
                    {
                        @Override public void onErrorResponse(VolleyError error) {
                            Log.d("Error.Response", error.toString());
                        }
                    }
                  );
                  VolleySingleton.getInstance(this).addToRequestQueue(getRequest); //Call to get dashboard feed
}

As you can see, I'm currently just logging out the response. I want to parse the Array though and display the results in a list view. The documentation for this isn't great, and I'm pretty green in terms of Android dev. What is the proper way to parse a JSON array from Volley and display the results in a list view? I've gatheredthat I should use parseNetworkResponse, but not sure how to implement.

如您所见,我目前只是注销响应。我想解析数组并在列表视图中显示结果。这方面的文档不是很好,而且我在 Android 开发方面很环保。从 Volley 解析 JSON 数组并在列表视图中显示结果的正确方法是什么?我收集到我应该使用parseNetworkResponse,但不确定如何实施。

采纳答案by Alexey Dmitriev

I'd recommend to stick to the GSON library for JSON parsing. Here's how a Volley request with embedded JSON processing could look then:

我建议坚持使用 GSON 库进行 JSON 解析。以下是带有嵌入式 JSON 处理的 Volley 请求的外观:

import java.io.UnsupportedEncodingException;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * Volley GET request which parses JSON server response into Java object.
 */
public class GsonRequest<T> extends Request<T> {

    /** JSON parsing engine */
    protected final Gson gson;

    /** class of type of response */
    protected final Class<T> clazz;

    /** result listener */
    private final Listener<T> listener;

    public GsonRequest(String url, Class<T> clazz, Listener<T> listener, 
            ErrorListener errorListener) {
        super(Method.GET, url, errorListener);

        this.clazz = clazz;
        this.listener = listener;
        this.gson = new Gson();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

Let's imagine you have a server method located at http://example.com/api/persons/which returns a JSON array of Person; Person is as follows:

假设您有一个位于http://example.com/api/persons/的服务器方法,它返回一个 Person 的 JSON 数组;人物如下:

public class Person {
    String firstName;
    String lastName;
}

We can call the abovementioned method like this:

我们可以这样调用上述方法:

GsonRequest<Person[]> getPersons = 
        new GsonRequest<Person[]>("http://example.com/api/persons/", Person[].class,

            new Listener<Person[]>() {
                @Override
                public void onResponse(Person[] response) {
                    List<Person> persons = Arrays.asList(response);
                    // TODO deal with persons
                }

            }, new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO deal with error
                }
            });

VolleyQueue.get().add(getPersons);

And finally in response listener we get an array of Person which can be converted to list and fed to ListView's adapter.

最后在响应侦听器中,我们得到一个 Person 数组,可以将其转换为列表并提供给 ListView 的适配器。

回答by Amin Bahiraei

you can use Gsonproject to working with json in java and android app ,it is so simple this link is a sample link of using gson

您可以使用Gson项目在 java 和 android 应用程序中使用 json,非常简单,此链接是使用 gson 的示例链接

How To Convert Java Object To / From JSON (Gson)

如何在 Java 对象和 JSON 之间转换 (Gson)

回答by SathMK

You can either use the native JSONParsorin the android framework your requirements are comparatively less and the JSONis simple. Hereis a link for the tutorial.

您可以使用原生JSONParsor的Android框架的要求相对较少且JSON简单的是教程的链接。

But if you are using complexJSONobjects, use libraries like

但是,如果您使用复杂的JSON对象,请使用类似的库

  • GSON
  • Hymanson
  • GSON
  • Hyman逊

I find GSONeasier and more effective to use. You know more about it from Here

我发现GSON使用起来更容易、更有效。你从这里了解更多