[英]How to parse this JSON response with GSON after a Retrofit GET request?
我試圖在改造GET請求后使用GSON解析JSON響應。 我不需要所有的鍵和值,因此只@Expose所需的鍵和值,並指示解析器執行此操作。 該請求會觸發OK,並且響應變得整潔,但是查看logcat時,我發現了這個錯誤,這顯然表明我指出POJO模型的格式或實現錯誤:
04-09 12:16:01.679 5604-5604 /? V / Retrofit錯誤:retrofit.converter.ConversionException:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:預期為BEGIN_ARRAY,但在第1行第2列路徑處為BEGIN_OBJECT $
這是JSON響應(在GET請求之后返回ok):
{
objects: [
{
rating: 0.97,
name: "High Line",
ranking: 0,
url: "http://www.thehighline.org",
price: null,
phone: "2125006035",
last_sync: 1428328869,
photos: [
"https://irs3.4sqi.net/img/general/original/11402168_2zKtnTfWXPJJJAaX7N6g1EMPTR7ahNqSAOsMotN-jNU.jpg"
],
local_id: 13778,
likes: 0,
city_id: 2621,
address: "btwn Gansevoort & W 34th St",
resource_uri: "/api/v1/venues/40f1d480f964a5206a0a1fe3/",
id: "40f1d480f964a5206a0a1fe3",
categories: [
{
name: "Park",
parent: {
local_id: 7,
name_id: "sights",
name: "Landmarks",
id: "4d4b7105d754a06377d81259"
},
local_id: 494,
name_id: "park",
category_id: 7,
id: "4bf58dd8d48988d163941735"
}
],
location: {
lat: 40.7470618874989,
lng: -74.0051937103271
}
},
{
rating: 0.97,
name: "Central Park",
ranking: 0,
url: "http://www.centralparknyc.org",
price: null,
phone: "2123106600",
last_sync: 1428521923,
photos: [
"https://irs2.4sqi.net/img/general/original/655018_Zp3vA90Sy4IIDApvfAo5KnDItoV0uEDZeST7bWT-qzk.jpg"
],
local_id: 13826,
likes: 0,
city_id: 2621,
address: "59th St to 110th St",
resource_uri: "/api/v1/venues/412d2800f964a520df0c1fe3/",
id: "412d2800f964a520df0c1fe3",
categories: [
{
name: "Park",
parent: {
local_id: 7,
name_id: "sights",
name: "Landmarks",
id: "4d4b7105d754a06377d81259"
},
local_id: 494,
name_id: "park",
category_id: 7,
id: "4bf58dd8d48988d163941735"
}
],
location: {
lat: 40.7888599444948,
lng: -73.9611625671387
}
}
],
meta: {
total_count: 1344,
next: "/api/v1/venues/?city_id=2621&category=topPicks&offset=2&limit=2&format=json",
limit: 2,
offset: 0
}
}
這是對Retrofit服務的主要活動調用:
Map<String, String> params = new HashMap<String, String>();
params.put("city_id", "2621");
params.put("offset", "0");
params.put("limit", "2");
params.put("category", "topPicks");
params.put("format", "json");
ApiClient.getApiClient().listVenues(params, new Callback<List<ApiResponse>>() {
@Override
public void success(List<ApiResponse> venues, Response response) {
//consumir venues
Log.v("RETROFIT SUCCESS", response.getBody().toString());
mAdapter = new MainCustomAdapter(venues);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void failure(RetrofitError retrofitError) {
if (retrofitError.getResponse() != null) {
Log.v("Retrofit error", retrofitError.getCause().toString());
}
//manejar el fallo
}
});
這是Api客戶端:
public class ApiClient {
private static ApiVenuesInterface apiVenues;
public static ApiVenuesInterface getApiClient() {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
if (apiVenues == null) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://endpoint.com")
.setConverter(new GsonConverter(gson))
.setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("RETROFIT"))
.build();
apiVenues = restAdapter.create(ApiVenuesInterface.class);
}
return apiVenues;
}
public interface ApiVenuesInterface {
//llamada asíncrona al querystring de venues
@GET("/api/v1/venues")
void listVenues(@QueryMap Map<String, String> params, Callback<List<ApiResponse>> callback);
}}
最后是我的POJO模型(我認為這是主要問題所在的地方):
public class ApiResponse {
private List<Object> objects = new ArrayList<Object>();
}
class Object {
@Expose
private String name;
@Expose
private List<String> photos = new ArrayList<String>();
@Expose
private String address;
@Expose
private List<Category> categories = new ArrayList<Category>();
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @return
* The photos
*/
public List<String> getPhotos() {
return photos;
}
/**
*
* @return
* The address
*/
public String getAddress() {
return address;
}
/**
*
* @return
* The categories
*/
public List<Category> getCategories() {
return categories;
}
class Category {
@Expose
private String name;
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
}}
因此,我該如何為POJO建模以解析所需的數據? 提前致謝。
重要編輯:此問題對Retrofit 1.x有效。 請注意,Retrofit 2.x與此稍有不同,因為它使用注釋和Call方法。
根據之前的評論:
快速瀏覽后,您的Callback
返回類型不是List<ApiResponse>
類型,而是ApiResponse
。 如果您更改以下內容,則事情應該開始進行:
public interface ApiVenuesInterface {
//llamada asíncrona al querystring de venues
@GET("/api/v1/venues")
void listVenues(@QueryMap Map<String, String> params, Callback<ApiResponse> callback);
}
目前,您正在告訴Gson將響應轉換為ApiResponse
對象的列表,但實際上,它只是包裝項目列表/數組的單個ApiResponse
。 您已經正確地為POJO建模,但沒有太多的改造回調。
[edit]回答您的后續問題:您只需在ApiResponse
類中添加getter即可訪問包裝的對象:
public List<Object> getObjects() {
return objects;
}
一個小提示:最好為您的Object
類命名一個不同的名稱,因為它的名稱與Java中所有對象的“母親”相同: java.lang.Object
。 這勢必導致混亂,並且非常容易導入/引用錯誤。 嘗試提出一些更具描述性的內容,例如Venue
(盡管您可能會誤解,但看來這就是您要處理的內容)。
[edit2] Gson產生一個ApiResponse
對象,該對象環繞List<Object>
。 可以像其他任何Java迭代一樣遍歷該列表。 即使用增強的for循環:
for (Object object : getObjects()) {
// get the name for this object
String name = object.getName();
// get the address for this object
String address = object.getAddress();
// get all the photo urls for this object
List<String> photos = object.getPhotos();
// etc...
}
之所以看到myjavapackage.Object@3c4a86e1
是因為Java不知道如何將對象表示為打印字符串。 您可以通過重寫Object
類中的以下方法來更改此表示形式:
@Override public String toString() {
// return a string representation for this object; i.e. its name:
return name;
}
我仍然建議將Object
類重命名為更明智的名稱,以避免將其與內置java.lang.Object
混淆。
嘗試從json字符串中刪除此部分
{對象:
最后一個花括號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.