I am receiving a Json object from web api,
it looks as follows:
{"Sites":[{"SiteId":1,"SiteName":"Site 1"},{"SiteId":2,"SiteName":"Site 2"},{"SiteId":3,"SiteName":"Site 3"}]}
Now I have the following code which uses gson to parse it to a POJO:
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
And here is my POJO:
public class UsersSitesViewModel
{
public List<UserSite> Sites;
}
public class UserSite {
public UserSite(int siteId, String siteName)
{
SiteId = siteId;
SiteName = siteName;
}
public int SiteId;
public String SiteName;
}
But now when I run in my code and I debug to look at the pojo it created:
it looks as follows:
WHy is it inseting 10 Null values into my array?
That is incorrect!
The reason you're seeing the ten null values is due to the way that Array Lists work. Array lists are essentially vectors, or things like act like arrays but automatically resize. To prevent extra amounts of copying memory around vectors (and ArrayLists) are generally created with additional memory. Since the time it takes to copy memory is larger than the time it takes to allocate memory at the beginning, most implementations just allocate extra space at the beginning.
We can tell that this is happening by the size
attribute inside the ArrayList. The size
is listed as 3
, which is the correct number of elements inside the array list. As such, when you query what the length of the array list is, you'll get 3
.