2013-04-01 58 views
0

我試圖獲得來自Facebook查詢響應,並將其映射到用戶定義的類:如何將Facebook響應轉換爲json格式的字符串?

我有以下類:

class FBStory { 
     @Field 
     private String application_id; 
     @Field 
     private String application_name; 
     @Field 
     private String caption; 
     @Field 
     private String created_time; 
     @Field 
     private String description; 
     @Field 
     private String from;// user_Id 
     @Field 
     private String message; 
     @Field 
     private String name; 
     @Field("objectId") 
     private String object_id; 
     @Field 
     private String privacy; 
     @Field("statusType") 
     private String status_type; 
     @Field 
     private String story; 
     @Field("storyId") 
     private String id; 
     @Field("storyUrl") 
     private String link; 
     @Field 
     private String type; 
     @Field 
     private String updated_time; 
     @Field 
     private Set<CommentInfo> comments = new HashSet<CommentInfo>();//set of comment Id 
     @Field 
     private Set<String> likes = new HashSet<String>(); 
     @Field("storyTags") 
     private Set<String> story_tags = new HashSet<String>(); 
} 

而對於查詢Facebook的迴應是:

Post[actions=[] application=null attribution=null caption=null comments=Comments[count=0 data=[]] createdTime=Mon Apr 01 08:16:28 IST 2013 description=null from=CategorizedFacebookType[category=null id=100000363414872 metadata=null name=Nitin Thokare type=null] icon=null id=100000363414872_555878751100900 likes=null likesCount=null link=null message=null messageTags={} metadata=null name=null objectId=null picture=null place=null privacy=Privacy[deny=null description=null friends=null networks=null value=] properties=[] source=null to=[] type=status updatedTime=Mon Apr 01 08:16:28 IST 2013 withTags=[]] 

我試圖將上述響應轉換爲使用以上類別的對象:

storyObj = gson.fromJson(restFBResponse.toString(), SolrFBStoryDoc.class); 

但對於gson.fromJson(),第一個參數應該是格式爲JSON的字符串。因此,我得到的代碼上面的行錯誤:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5 

有沒有什麼辦法讓我可以轉換restFBResponse到一個適當Json字符串,然後傳遞作爲第一個參數gson.fromJson()

回答

0

我發現使用Solr Beans是可能的,但是使用Solr beans引發了它自己的問題,其中一個問題如討論here。所以,爲了克服這個問題,我收到了來自Facebook的JsonObject.class格式(即connectionType)的響應,而不是Post.class,如下所示:

data = facebookClient.fetchConnection(connection, t, parameters) 

where, 'fetchConnection' is defined as, 

<T> Connection<T> fetchConnection(String connection, Class<T> connectionType, Parameter... parameters); 
相關問題