NiTiN
NiTiN

Reputation: 1022

gson.fromJson - deserialization failing

I am facing issues with deserialization since I use same object structure for two different web-response. In 'search', I get array of object, and in 'details' I get just one object.

Search Code:

InputStream source = Helper.retrieveStream("http://<domainname>/search.jsp?action=search&q=" + query);
Reader reader = new InputStreamReader(source);
Gson gson = new Gson();
SearchObj searchResponse = gson.fromJson(reader, SearchObj.class); 

Details Code:

InputStream source = Helper.retrieveStream("http://<domainname>/search.jsp?action=detail&id=" + id);

From services I get response with same object hireachy TopObject -> SearchResponse -> Response, but in first case (Search) I get array of Response[] and in second case (Details) I get single Response object.

Obiviously, my deserialization fails in second scenario since code is expecting array of Response instead of just one response.

I realized that I can not change name of the object like I can change name of the properties with annotation @SerializedName.

Any suggestion?

Upvotes: 2

Views: 2229

Answers (1)

Programmer Bruce
Programmer Bruce

Reputation: 66943

Using Gson, to deserialize such JSON that is sometimes an array and sometimes an object would require custom deserialization. This specific issue has been covered in previous StackOverflow threads, such as Parsing JSON with GSON, object sometimes contains list sometimes contains object.

Upvotes: 1

Related Questions