2

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?

NiTiN
  • 1,022
  • 1
  • 16
  • 25
  • Make another domain object and treat them separately, TopObject -> SearchResponse -> Response[] & TopObject -> DetailsResponse -> Response. – yorkw Nov 07 '11 at 19:20
  • since I can not annotate the classname, how can I handle "Response" object and "Response[]" array-of-object separately? – NiTiN Nov 07 '11 at 20:20
  • Perhaps you could paste the JSON source of both responses? Also please paste your object heirarchy. Thanks – Tyler Nov 10 '11 at 01:13

1 Answers1

1

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.

Community
  • 1
  • 1
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97