I am currently writing an RSS feed parser in Java using Gson. I convert RSS-XML to JSON, and then later use Gson to deserialize JSON to Java POJO (somewhat roundabout, but there is a reason for this). Everything worked fine, like deserialization for channel # 1 ( BBC ) below, but for feed # 2 ( NPR ) below, I started getting exceptions from thrown.
I think I have identified the problem, but I'm not sure how to solve it:
A problem occurs with these two RSS feeds (for example):
For these different RSS feeds, a field called "guid" is returned as either: a) an object with two fields (as in the BBC RSS Feed), or b) a string (as in the NPR RSS feed ).
Here are some paraphrase versions of the corresponding JSON:
BBC RSS Feed
// is returning 'guid' as an object "item" : [ { // omitted other fields for brevity "guid" : { "isPermalink" : false, "content" : "http:\/\/www.bbc.co.uk\/news\/uk-england-33745057" }, }, { // ... } ]
NPR RSS Feed
// is returning 'guid' as a string "item" : [ { // omitted other fields for brevity "guid" : "http:\/\/www.npr.org\/sections\/thetwo-way\/2015\/07\/31\/428188125\/chimps-in-habeas-corpus-case-will-no-longer-be-used-for-research?utm_medium=RSS&utm_campaign=news" }, { // ... } ]
I model this in Java as follows:
// RSSFeedItem.java private Guid guid; // GUID.java private boolean isPermalink; private String content;
So in this case, it works fine when called
Gson gson = new Gson(); RssFeed rssFeed = gson.fromJson(jsonData, RssFeed.class);
for the BBC RSS feed , but it throws an exception when parsing the NPR RSS feed .
The specific error that led me to the conclusion that this is a type error was as follows (when trying to deserialize the NPR RSS feed ):
Severe: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 673 path $.rss.channel.item[0].guid
So, one way or another: how can I handle this situation with Gson, where the field is returned as potentially different data types? I suppose there might be some kind of trick or annotation that I could use to do this, but I'm not sure, and after checking the documentation for Gson, I could not find an easily accessible answer.