使用Retrofit和GSON解析JSON,尝试解析和获取回调时出错. [英] Parsing JSON with Retrofit and GSON, error when trying to parse and obtain callback.

查看:121
本文介绍了使用Retrofit和GSON解析JSON,尝试解析和获取回调时出错.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用翻新功能来处理对Android应用程序的API的调用.我试图让Retrofit处理JSON的解析,并根据我创建的POJO创建对象列表.

I am using to Retrofit to handle Calls to my API for an Android Application. I am trying to get Retrofit to handle the parsing of the JSON, and creating a list of Objects in accordance with the POJO i have created.

我收到的错误是" com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为字符串,但在第1行第176列处为BEGIN_OBJECT".

我使用JsonSchema2Pojo生成了我的java类.这些类和关联的JSON如下.

I used JsonSchema2Pojo to generate my java classes. The classes and associated JSON are as follows.

{"status":"success","data":[{"sort_key":1,"event_id":1947357,"title":"2014 US Open Tennis Session 15 (Mens\/Womens Round of 16)","datetime_utc":"2014-09-01T15:00:00","venue":{"city":"Flushing","name":"Louis Armstrong Stadium","extended_address":"Flushing, NY 11368","url":"https:\/\/seatgeek.com\/venues\/louis-armstrong-stadium\/tickets\/?aid=10918","country":"US","display_location":"Flushing, NY","links":[],"slug":"louis-armstrong-stadium","state":"NY","score":0.73523,"postal_code":"11368","location":{"lat":40.7636,"lon":-73.83},"address":"1 Flushing Meadows Corona Park Road","timezone":"America\/New_York","id":2979},"images":["https:\/\/chairnerd.global.ssl.fastly.net\/images\/performers-landscape\/us-open-tennis-45e2d9\/5702\/huge.jpg","https:\/\/chairnerd.global.ssl.fastly.net\/images\/performers\/5702\/us-open-tennis-c1ccf7\/medium.jpg","https:\/\/chairnerd.global.ssl.fastly.net\/images\/performers\/5702\/us-open-tennis-01f513\/large.jpg","https:\/\/chairnerd.global.ssl.fastly.net\/images\/performers\/5702\/us-open-tennis-4e07f2\/small.jpg"]}

据此,我相信我需要生成3个POJO,我的更高级别的"EventObject"类,一个Location类和一个Venue类.这些类及其变量如下:

From this i believe i need to generate 3 POJO's, my higher level "EventObject" Class, A Location Class, and a Venue Class. These classes and their variables follow:

EventObject类:

EventObject Class:

public class EventObject {

private Integer sortKey;
private Integer eventId;
private String title;
private String datetimeUtc;
private Venue venue;
private List<String> images = new ArrayList<String>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

位置类别:

public class Location {

private Float lat;
private Float lon;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

地点班级:

public class Venue {

private String city;
private String name;
private String extendedAddress;
private String url;
private String country;
private String displayLocation;
private List<Object> links = new ArrayList<Object>();
private String slug;
private String state;
private Float score;
private String postalCode;
private Location location;
private String address;
private String timezone;
private Integer id;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

我的Api呼叫界面如下:

My interface for the Api Call is as follows:

public interface UserEvents {

@GET("/user/get_events")
void getEvents(@Header("Authorization")String token_id,
@Query("event_type")String event_type,
@Query("postal_code")int postalCode,
@Query("per_page") int perPage ,
@Query("lat") int lat,
@Query("lon") int lon,
@Query("month")int month,
@Query("page")int page,
Callback<List<EventObject>>callback) ;

}

这是我的代码中的实现:

Here is its implementation in my code :

UserEvents mUserEvents = mRestAdapter.create(UserEvents.class);
mUserEvents.getEvents(token_Id, "sports",11209,25,0, 0, 9, 2, new Callback <List<EventObject>>() {
@Override
public void success(List<EventObject> eventObjects, retrofit.client.Response response) {
Log.d(TAG,"Success");
            }

这里发生了很多事情,但是我相信我处理JSON的方式可能出了问题.当我将JSON复制并粘贴到Pojo生成器时,我没有包含状态:成功",数据:{

There is alot going on here, but i believe that i am probably going wrong with how i am handling the JSON. When i copied and pasted in my JSON to the Pojo generator, i did not include "status:success, " data:{

我实际上只是使用了Array中某个元素的整个条目(从{sort_key到下一个sort key的所有内容),并将其推入转换器.

I essentially just used the entire entry of an element in the Array ( everything from {sort_key onward until the next sort key ) and pushed that through the converter.

这是我对Retrofit和API的首次尝试,并且解析任何复杂的内容. 我希望其他人能够指出这一点.我也用谷歌搜索,没有运气就可以解决这个问题.

This is my first try at Retrofit and API work, and parsing anything this complicated. I am hoping its something that someone else will be able to point out. I have googled as well i could to sort this out with no luck.

感谢您的光临.

推荐答案

主要问题是您没有获得响应的根元素.您需要创建一个实体响应",以获取项目状态和数据.看起来像这样:

The main problem is that you are not getting the root element of the response. You need to create an entity "response" that gets the items status and data. It would look something like this:

public class RootObject {

    @Expose
    private String status;
    @Expose
    private EventObject data;

    //getters and setters here
}

然后,当您进行回调时,应指向您的RootObject,mUserEvents.getEvents(token_Id, "sports",11209,25,0, 0, 9, 2, new Callback <RootObject>()

Then when you make the callback you should point to your RootObject, mUserEvents.getEvents(token_Id, "sports",11209,25,0, 0, 9, 2, new Callback <RootObject>()

另一件事,Retrofit使用GSON解析您的json响应.这意味着在创建实体时,变量需要匹配响应中出现的对象的名称.如果不是,则需要告诉GSON如何映射变量,如下所示:

One more thing, Retrofit uses GSON to parse your json reponse. It means that when you create the entities, the variables need to match the name of the objects coming in the response. If it doesn't you need to tell GSON how to map the variables, like this:

@SerializedName("extended_address")
@Expose
private String extendedAddress;

在这种情况下,json中输入的值是"extended_address",并将被映射到字符串ExtendedAddress.如果不放置@SerializedName行,则解析将失败.如果要跳过该行,则可以调用变量"extended_address",使其与响应匹配.

In that case the value coming in the json is "extended_address" and will be mapped to the String extendedAddress. If you don't put that @SerializedName line the parsing will fail. If you want to skip that line then you can call your variable "extended_address" so it matches the response.

GSON需要@Expose来解析其下面的变量.如果没有变量,则GSON将忽略该解析.因此,您需要在实体上同时修复@Expose@SerializedName,以便GSON正常工作.

The @Expose is needed by GSON to parse the variable below it. If a variable doesn't have it then GSON will ignore that parsing. So you need to fix both the @Expose and @SerializedName on your entities so GSON works correctly.

希望有帮助.

这篇关于使用Retrofit和GSON解析JSON,尝试解析和获取回调时出错.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆