[英]Parse Android Volley JSONArray response
我正在向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
}
如您所見,我目前只是在退出響應。 我想解析數組,並在列表視圖中顯示結果。 這方面的文檔並不是很好,我在Android開發方面非常環保。 從Volley解析JSON數組並在列表視圖中顯示結果的正確方法是什么? 我已經收集到我應該使用parseNetworkResponse
,但不知道如何實現。
我建議堅持使用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));
}
}
}
讓我們假設你有一個位於http://example.com/api/persons/的服務器方法,它返回一個Person的JSON數組; 人如下:
public class Person {
String firstName;
String lastName;
}
我們可以這樣稱呼上述方法:
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);
最后在響應偵聽器中,我們得到一個Person數組,可以將其轉換為list並饋送到ListView的適配器。
你可以使用Gson項目在java和android app中使用json,它很簡單這個鏈接是使用gson的示例鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.