简体   繁体   English

使用Retrofit和GSON解析JSON时,尝试解析并获取回调时出错。

[英]Parsing JSON with Retrofit and GSON, error when trying to parse and obtain callback.

I am using to Retrofit to handle Calls to my API for an Android Application. 我正在使用Retrofit处理针对Android应用程序的API调用。 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. 我试图让Retrofit处理JSON的解析,并根据我创建的POJO创建一个对象列表。

The error i receive is " com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 176". 我收到的错误是“ com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期字符串但在第1行第176行是BEGIN_OBJECT”。

I used JsonSchema2Pojo to generate my java classes. 我使用JsonSchema2Pojo来生成我的java类。 The classes and associated JSON are as follows. 类和关联的JSON如下所示。

{"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"]}

From this i believe i need to generate 3 POJO's, my higher level "EventObject" Class, A Location Class, and a Venue Class. 从此我相信我需要生成3个POJO,我的更高级别的“EventObject”类,位置类和Venue类。 These classes and their variables follow: 这些类及其变量如下:

EventObject Class: EventObject类:

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

Location Class: 位置等级:

public class Location {

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

Venue Class: 地点类别:

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

My interface for the Api Call is as follows: 我的Api Call界面如下:

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");
            }

There is alot going on here, but i believe that i am probably going wrong with how i am handling the JSON. 这里有很多,但我相信我可能会错误地处理JSON。 When i copied and pasted in my JSON to the Pojo generator, i did not include "status:success, " data:{ 当我将我的JSON复制并粘贴到Pojo生成器时,我没有包含“status:success”数据:{

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. 我基本上只使用了数组中元素的整个条目(从{sort_key向前到下一个排序键的所有内容)并将其推送到转换器中。

This is my first try at Retrofit and API work, and parsing anything this complicated. 这是我第一次尝试Retrofit和API工作,并解析任何复杂的东西。 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. 我也用Google搜索,我可以把它排除在外,没有运气。

Thanks for looking. 谢谢你的期待。

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
}

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>() 然后当你进行回调时,你应该指向你的RootObject, mUserEvents.getEvents(token_Id, "sports",11209,25,0, 0, 9, 2, new Callback <RootObject>()

One more thing, Retrofit uses GSON to parse your json reponse. 还有一件事,Retrofit使用GSON来解析你的json响应。 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: 如果不是,你需要告诉GSON如何映射变量,如下所示:

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

In that case the value coming in the json is "extended_address" and will be mapped to the String extendedAddress. 在这种情况下,json中的值是“extended_address”,并将映射到String extendedAddress。 If you don't put that @SerializedName line the parsing will fail. 如果不放置@SerializedName行,则解析将失败。 If you want to skip that line then you can call your variable "extended_address" so it matches the response. 如果要跳过该行,则可以调用变量“extended_address”,使其与响应匹配。

The @Expose is needed by GSON to parse the variable below it. @Expose需要@Expose来解析它下面的变量。 If a variable doesn't have it then GSON will ignore that parsing. 如果变量没有变量,那么GSON将忽略该解析。 So you need to fix both the @Expose and @SerializedName on your entities so GSON works correctly. 因此,您需要在实体上修复@Expose@SerializedName ,以便GSON正常工作。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM